<?php
 //require_once 'Excel/reader.php';
Zend_Loader::loadClass("BaseControllerAuth");
class AccountController extends BaseControllerAuth
{
	public function initialize()
	{
		$this->setLayout("account");
		$this->assign("pageTitle","Trade Management System " . $this->getConfig()->client->name);
		$this->bypassAuth("uploadFileFromLocal");
		$this->bypassAuth("dumpmasterfile");
		$this->bypassAuth("checkorg");
	}
	
	public function indexAction() {
		
		Zend_Loader::loadClass("UserType");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AuthUtility");
		Zend_Loader::loadClass("MenuUtility");
	
		
		
		$viewType = $this->getParam("view");
		
		$userTypes = new UserType();
		$userTypesArray = $userTypes->getUserTypesArray("code", "id");
		
		
		$auth = BaseAuth::getInstance();
  		$this->assign("username",$auth->username);
		
		$menuUtility = new MenuUtility();
		$this->assign("menuUtility" ,$menuUtility);
		$this->assign("viewType",$viewType);	
		
		switch($viewType) { 
			case $userTypesArray[CodesUtility::USER_TYPE_IMPORTER]:
				$this->render("importer.tpl");
				break;	
			case $userTypesArray[CodesUtility::USER_TYPE_EXPORTER]:
				$this->render("exporter.tpl");
				break;	
		}
		
		
	}
	public function manageupdateAction() {
		Zend_Loader::loadClass("Organisms");
		print "starting organism attribute updates...";
		
		$managed = new Organisms();
		$managed->updateAttributes();

		die();
	}
	public function createorderAction(){
	
		Zend_Loader::loadClass("Countries");
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("OrganismGroups");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		
		
		$cart = CartUtility::getSearchCart();
		$items = $cart->items;
		
		$auth = BaseAuth::getInstance();
		
		$userTypes = new UserTypes();
		
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$organismGroup = new OrganismGroups();
				$groupValue = $organismGroup->getOrganismGroupsByOrgId($auth->org_id);	
				$this->assign("groups",$groupValue);
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$countries = new Countries();
				$countries->loadWhere("1 = 1",array("country"));
				$this->assign("countries",$countries->toArray());
				break;
		}
		
		if(isset($items['list'])) {

			$this->assign("cart",1);
			$this->assign("country_code",$items['country_code']);
			$this->assign("organisms",$items['searchList']);
			$this->assign("organism_id",$items['organism_id']);
		}
		
		$this->setNoLayout();
		
		$this->render('order.tpl');
	}
	
	public function adminProfileAction() {
		
		Zend_Loader::loadClass("AuthUtility");
		Zend_loader::loadClass("Organization");
		Zend_Loader::loadClass("CodesUtility");
	
		$auth = BaseAuth::getInstance();
		
		// $addressType = $this->getParam("addressType");
		
	
		$organization = new Organization();
		$organization->clear;
		$organization->loadWhere("org_id = ". $auth->org_id);
		$this->assign("name",$organization->name);
		$this->assign("trading_name",$organization->trading_name);
		$this->assign("phone",$organization->phone);
		$this->assign("fax",$organization->fax);
		$this->assign("email",$organization->email);
		$this->assign("orgType",$organization->org_type);
		
		$organization->clear;
		$orgValues = $organization->getAddressByOrgId($auth->org_id);
		$orgContacts = $organization->getContactByOrgId($auth->org_id);
		$orgPayments = $organization->getPaymentInformationByOrgId($auth->org_id);
		$this->assign("addressValue",$orgValues);
		$this->assign("contactValue",$orgContacts);
		$this->assign("paymentsValue",$orgPayments);
			
		//echo "<pre>";print_r($orgValues);echo "</pre>";
		
		$this->setNoLayout();
		$this->render("admin.tpl");
		
	}
	

	public function searchorganismGroupByCountryAction() {
		Zend_Loader::loadClass("OrganizationOrganisms");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$country_code = $this->getParam("country_code");
		
		$organisms = new OrganizationOrganisms();
		$auth = BaseAuth::getInstance();
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$totype = CodesUtility::USER_TYPE_FMA;
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$totype = CodesUtility::USER_TYPE_EXPORTER;
				break;
		}
		
		$organismValues = $organisms->getOrganismByCountry($country_code,$totype,0,0,'','grp.organism_group_id');
		//echo "<pre>"; print_r($organismValues); echo "</pre>";
		$this->assign("organisms",$organismValues);
		$this->setNoLayout();
		$this->render("organismbygroup.tpl");
				
	}
	
	public function searchorganismByCountryAction(){
	
		Zend_Loader::loadClass("OrganizationOrganisms");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$country_code = $this->getParam("country_code");
		$group_id = $this->getParam("groupid");
		
		
		$organisms = new OrganizationOrganisms();
		$auth = BaseAuth::getInstance();
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$totype = CodesUtility::USER_TYPE_FMA;
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$totype = CodesUtility::USER_TYPE_EXPORTER;
				break;
		}
		
		$organismValues = $organisms->getOrganismByCountry($country_code,$totype,0,$group_id,'','organism.organism_id');		
		

		$cart = CartUtility::getSearchCart();
		$items = $cart->items;
		$items['searchList'] = $organismValues;
		
		$cart->items = $items;
		
		
		$this->assign("organisms",$organismValues);
		$this->setNoLayout();
		$this->render("organismbycountry.tpl");
	}
	
	public function viewOrganismAction(){
	
		Zend_Loader::loadClass("OrganizationOrganisms");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("PageUtility");
		Zend_Loader::loadClass("DataUtility");
		
		$cart = CartUtility::getSearchCart();
		$items = $cart->items;
		
		$organism_id = 0;
		$searchFlg = 0;
		$country_code = $this->getParam("country_code");
		//$organism_id = $this->getParam("organism_id") ? $this->getParam("organism_id") : 0;
		$searchFlg = $this->getParam("searchFlg") ? $this->getParam("searchFlg"): 0 ;
		
		$search = $this->getParam("search");

		$ret_flag = 0;
		if (isset($search['country'])) {
			$country_code = $search['country'];
		} else { 
			$country_code = 'none';
		}
	
		if (isset($search['organism'])) {
			$organism_id = $search['organism'];
			$ret_flag = 1;
		} else {
			$organism_id = 0;
		}
		
		if (isset($search['group'])) {
			$groupid = $search['group'];
			$ret_flag = 1;
		} else {
			$groupid = 0;
		}
		if (isset($search['criteria'])) {
			$criteria = $search['criteria'];
			$ret_flag = 1;
		} else {
			$criteria = "";
		}
			
		if(isset( $items['organism_id']  )  && $searchFlg == 0 ) {
			//echo "</pre>";print_r($items['list']);echo "</pre>";
			$this->assign("organisms",$items['list']);
			$this->assign("country_code",$items['country_code']);	
		} else {
			
			
			$organisms = new OrganizationOrganisms();
			
			$auth = BaseAuth::getInstance();

			$userTypes = new UserTypes();
			$userTypesArray = $userTypes->getUserTypesArray("id", "code");			

			$org_type = $userTypesArray[$auth->user_type_id];
			switch($org_type) {
				case CodesUtility::USER_TYPE_EXPORTER:
					$totype = CodesUtility::USER_TYPE_FMA;
					break;
				case CodesUtility::USER_TYPE_IMPORTER:
					$totype = CodesUtility::USER_TYPE_EXPORTER;
					break;
			}	
		
			//$organismValues = $organisms->getOrganismByCountry($country_code,$totype,$organism_id,$groupid,$criteria,'',1,1);
			$condition = "";
			$data_utils = new DataUtility();
			
			if ($org_type <> CodesUtility::USER_TYPE_EXPORTER) {
				$condition = "o.country_code = '".$country_code."'";
			}
			if (strlen($groupid) > 0) {		
				if (strlen($condition) > 0) {	
					$condition = $condition." AND o.organism_group_id = ".$groupid;
				} else {
					$condition = "o.organism_group_id = ".$groupid;
				}
				
			}
			if(isset($criteria) && strlen($criteria) > 0){
				if (strlen($condition) > 0) {
					$condition = $condition." AND (o.name like  '%". $criteria . "%' OR o.scientific_name like '%". $criteria . "%')" ;
				} else {
					$condition = "(o.name like  '%". $criteria . "%' OR o.scientific_name like '%". $criteria . "%')" ;
				}
			}	
			if (isset($search['organism']) && $search['organism'] > 0) {
				$condition = $condition." AND o.organism_id = ".$search['organism'];
			}					
			$params = array('user_type' => $totype, 'condition' => $condition);

			$organismValues = $data_utils->find_Organisms($auth->org_id, "by_user_type", $params);
			
			//echo "<pre>";print_r($organismValues);echo "</pre>";die();

			$list = PageUtility::pagination($organismValues,15,0);
			
			$pagelist = array();

			$pagelist['pagelength'] = PageUtility::pagelength(10,round(count($organismValues)/15));
			$pagelist['action'] = "/account/orderorganismlist";
			
			$this->assign("pagelist",$pagelist);
			
			$data = array();
			
			$data['list'] = $organismValues;
			$data['country_code'] = $country_code;
			$data['organism_id'] = $organism_id;
			$data['searchList'] = $items['searchList'];
			
			$cart->items = null;
			$cart->items = $data;
			//echo "<pre>";print_r($data);echo "</pre>";
			
			$this->assign("organisms",$list);
			$this->assign("country_code",$country_code);
		}	

		$this->setNoLayout();
		$this->render("organismlist.tpl");
		
	}
	
	public function orderorganismlistAction(){
	
		Zend_loader::loadClass("CartUtility");
		Zend_loader::loadClass("PageUtility");
		
		$page = $this->getParam("page");
		$cart = CartUtility::getSearchCart();
		$items = $cart->items;
		
		$list = PageUtility::pagination($items['list'],6,$page);
		
		$this->assign("organisms",$list);
		$this->setNoLayout();
		$this->render("pageorganismlist.tpl");
		
	}
	
	public function selectSupplierAction(){
	
		Zend_Loader::loadClass("OrganizationOrganisms");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("Organism");
		Zend_Loader::loadClass("Organismsizes");
		
		$country_code = $this->getParam("country_code");
		$organism_id = $this->getParam("organism_id");
		$key = $this->getParam("key");
		$gender = $this->getParam("gender");
		$size = $this->getParam("size");
		$amount = $this->getParam("amount");
		$currency = $this->getParam("currency");
	
		$cart = CartUtility::getPublicCart();
		
	
		$getOrder =  CartUtility::getOrderCart();
		$orders = $getOrder->items;
		
		//echo "<pre>"; print_r($orders); echo "</pre>;";
		
		$sizearray = new Organismsizes();
		$sizearray->load();
		if(count($orders)) {
			$order = array();
			$sizes = array();
			foreach($orders as $supplierkey => $suppItem) {
				foreach($suppItem['organismItem'] as $organismidKey => $organismsItem) {
					$orderqty = 0;
					if($organismidKey == $organism_id) {
						//foreach($suppItem['order']  as $orderkey => $ordervalue){
						$order[$supplierkey] = $organismsItem['order'];
						$sizes[$supplierkey] = $organismsItem['sizes'];
						//}
					}
				}
			}
			
			$this->assign("order",$order);
			$this->assign("sizes",$sizes);
		
		} 
			
			$organisms = new OrganizationOrganisms();
			$auth = BaseAuth::getInstance();
		
			$userTypes = new UserTypes();
			$userTypesArray = $userTypes->getUserTypesArray("id", "code");
			$org_type = $userTypesArray[$auth->user_type_id];
			switch($org_type) {
				case CodesUtility::USER_TYPE_EXPORTER:
					$totype = CodesUtility::USER_TYPE_FMA;
					break;
				case CodesUtility::USER_TYPE_IMPORTER:
					$totype = CodesUtility::USER_TYPE_EXPORTER;
					break;
			}
			
		
		if(strlen($country_code) == 0) {
			// set the default to PNG if no country code
			
			$country_code = "PG";
//			Zend_Loader::loadClass("Organization");
//
//			$organization = new Organization();
//
//			$orgValue = $organization->getAddressByOrgId($auth->org_id);
//
//			$country_code = $orgValue[0]['country_code'];

		}
		
		$this->assign("sizearray",$sizearray->toArray());
		$organismValues = $organisms->getOrganismByCountry($country_code,$totype,$organism_id,0,"","org.org_id");
		$cart->items = $organismValues;
		//echo "<pre>";print_r($organismValues);echo "</pre>";
		$this->assign("suppliers",$organismValues);
		
		$this->setLayout("accounts-inner.tpl");
		$this->assign("gender",$gender);
		$this->assign("size",$size);
		$this->assign("amount",$amount);
		$this->assign("currency",$currency);		
		$this->assign("organism_id",$organism_id);
		$this->assign("key",$key);
		$this->assign("country_code",$country_code);
		$this->render("selectsupplier.tpl");
		
	}
	
	public function saveorderAction(){
	
		// key = supplier  value = qty
		// format supplier
		//		 => array	( organism => value,order=array() ) ; 
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("Organismsize");
		
		$organismsize = new Organismsize();
		
		$gender = $this->getParam("gender");
		$size = $this->getParam("size");
		$amount = $this->getParam("amount");
		$currency = $this->getParam("currency");		
		$userValue = $this->getParam("user");
		$organism_id = $this->getParam("organism_id");
		
		$cart = CartUtility::getPublicCart();
		$items = $cart->items;
		
		$getOrder =  CartUtility::getOrderCart();
		$orders = $getOrder->items;
		foreach($userValue as $supplier => $value){
				$index = explode("_",$supplier);
				$type = $index[0];
				$supplier = $index[1];
				$key = $index[2];
				$org_organism_id = $index[3];
				if($value > 0 || !empty($value)) {
					if($type =='supplier') {
						if(!isset($orders[$supplier]['organismItem'][$organism_id])) {
							$orders[$supplier]['organismItem'][$organism_id] = $items[$key];
							$orders[$supplier]['supplier'] = $items[$key]['supplier'];
						}
							$orders[$supplier]['organismItem'][$organism_id]['order'][$size.'_'.$gender] = $value;
							$orders[$supplier]['organismItem'][$organism_id]['prices'][$size.'_'.$gender] = $amount;
							$orders[$supplier]['organismItem'][$organism_id]['currencies'][$size.'_'.$gender] = $currency;
							$orders[$supplier]['totalorder'] += $value;
					} else {
						  if(isset($orders[$supplier]['organismItem'][$organism_id])) {
							  $organismsize->clear();
							  $organismsize->loadWhere("size_code = '". $value . "'");
							  $orders[$supplier]['organismItem'][$organism_id]['sizes'][$size.'_'.$gender] = $value;
							  $orders[$supplier]['organismItem'][$organism_id]['prices'][$size.'_'.$gender] = $amount;
							  $orders[$supplier]['organismItem'][$organism_id]['currencies'][$size.'_'.$gender] = $currency;
							  //$orders[$supplier]['organismItem'][$organism_id]['size'] =$organismsize->size;
							  //$orders[$supplier]['organismItem'][$organism_id]['size_code'] =$value;
						  }
						
					}
				}
		}
		$getOrder->items = $orders;
		
		//$this->setLayout("ajax.tpl");
		//$this->assign("function","viewOrganism");
		//$this->setLayout("popupclose");
		//$this->assign("closeonly",1);
		//$this->render("..\globals\blank.tpl");
		
		
	}
	
	public function showCartAction(){
	
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Sizes");
		
		$organization = new Organization();
		$size = new Sizes();
		
		$sizeValue=$size->getSize();
		$cart = CartUtility::getOrderCart();
		
		//get the sizes and then assign
		//print_r($cart->items);die();
		$this->assign("orders",$cart->items);
	
		//echo "<pre>";print_r($size->toArray());echo "</pre>";
		$this->assign("size",$sizeValue);
		$this->setNoLayout();
		$this->render("showcart.tpl");
	}
	
	public function clearCartAction(){
		Zend_Loader::loadClass("CartUtility");	
		
		$cart = CartUtility::getOrderCart();
		$cart->items = null;
		$this->setNoLayout();
		//$this->_redirect("/account/showCart");
		// -redirect code
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Sizes");
		
		$organization = new Organization();
		$size = new Sizes();
		
		$sizeValue=$size->getSize();
		$cart = CartUtility::getOrderCart();
		
		$this->assign("orders",$cart->items);
	
		//echo "<pre>";print_r($size->toArray());echo "</pre>";
		$this->assign("size",$sizeValue);
		$this->setNoLayout();
		$this->render("showcart.tpl");
		// ---------
	}
	
	public function updateCartAction(){
		
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AccountUtility");
		
		$userValues = $this->getParam("user");
		$deleteValues = $this->getParam("delete");
		$blanketpo = $this->getParam("blanket_po");
		$cart = CartUtility::getOrderCart();
		$items = $cart->items;
		 
		$acctUtility = new AccountUtility();
		$newitems = $acctUtility->updateCart($items,$userValues,$deleteValues,$blanketpo);
		
	
		$cart->items = $newitems;
		//$this->_redirect("/account/showCart");		
		//-- redirect code
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Sizes");
		
		$organization = new Organization();
		$size = new Sizes();
		
		$sizeValue=$size->getSize();
		$cart = CartUtility::getOrderCart();
		
		$this->assign("orders",$cart->items);
	
		//echo "<pre>";print_r($size->toArray());echo "</pre>";
		$this->assign("size",$sizeValue);
		$this->setNoLayout();
		$this->render("showcart.tpl");
		// --
		
	}
	
	public function popupPaymentAction() {
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("purchaseOrder");
		$auth = BaseAuth::getInstance();
	
		$poid = $this->getParam("poid");
		$supplier_org_id = $this->getParam("supplier_org_id");
		
		$payment_info = new Organization();
		$org_payment_information = $payment_info->getActivePaymentInformation($supplier_org_id);	
		
		$po_header = new purchaseOrder();	
		$po_header_info = $po_header->getPurchaseOrderHeader($poid, $auth->org_id);
		$paymentInfo['notice'] = "";
		if (count($org_payment_information) > 0) {
			$paymentInfo['notice'] = str_replace("\n", "<br>", $org_payment_information[0]['content']);
		}
		$paymentInfo['reference_no'] = $po_header_info[0]['po_no'];		
		
		$this->assign("supplierpaymentinfo",$paymentInfo);
		$this->setNoLayout();
		$this->render('paymentpopup.tpl');	
	}
	
	public function savepopupPaymentAction(){
		Zend_Loader::loadClass("AccountUtility");
		$acctUtility = new AccountUtility;
		
		$userValues = $this->getParam("user");		
		
		$acctUtility->saveToPayment($userValues);
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/viewOrders/blanketpo/0/page/1')");
		$this->render("empty.tpl");
	}
	
	public function proceedPaymentAction(){
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AccountUtility");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Referencedefaults");
		
		$userValues = $this->getParam("user");
		$deleteValues = $this->getParam("delete");
		$blanketpo = $this->getParam("blanket_po");
		$cart = CartUtility::getOrderCart();
		$items = $cart->items;
		
		$paymentInfo = array();
		
		$acctUtility = new AccountUtility();
		$newitems = $acctUtility->updateCart($items,$userValues,$deleteValues,$blanketpo);
		$cart->items = $newitems;
		
		//get supplier org_id		
		foreach ($userValues as $userkey => $values){
			$indexkey = explode('|',$userkey);
			$supplier_org_id = $indexkey[0];
		}		
		$payment_info = new Organization();
		$org_payment_information = $payment_info->getActivePaymentInformation($supplier_org_id);
		
		$auth = BaseAuth::getInstance();
		
		$refdefault = new Referencedefaults(); 
		$rrdefault = $refdefault->getPONumber($auth->org_id);

		if ($rrdefault[0]['id']) {
			$po_prefix = $rrdefault[0]['po_prefix'];
			$next_po_no = $rrdefault[0]['next_po_no'];
		} else {
			$po_prefix = CodesUtility::PO_PREFIX;
			$next_po_no = CodesUtility::PO_START_PO_NO;		
		}
		$paymentInfo['notice'] = str_replace("\n", "<br>", $org_payment_information[0]['content']);
		$paymentInfo['reference_no'] = $po_prefix.$next_po_no;
		
		$this->assign("supplierpaymentinfo",$paymentInfo);

		$this->assign("orders",$newitems);
		$this->setNoLayout();
		$this->render('payment.tpl');
	}
	
	public function submitPaymentAction(){
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AccountUtility");
		
		$paymentInformation = $this->getParam("user");
		$deleteValues = $this->getParam("delete");

		$cart = CartUtility::getOrderCart();
		$items = $cart->items;
		$special_order = $cart->special_order;
		
		$acctUtility = new AccountUtility;
		$acctUtility->saveToPo($special_order, $items, $paymentInformation);

		$cart->items = null;

		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("Countries");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		
		$blanketpo = $this->getParam("blanketpo");
		
		$auth = BaseAuth::getInstance();
		$orders = new purchaseOrders();
		$ordersValues =$orders->getOrderByOrg($auth->org_id,$blanketpo);
		
		$countries = new Countries();
		$countryValue = $countries->getCountries(array(0=>'country_code',1=>'country'));
		
		$auth = BaseAuth::getInstance();
		
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$totype = CodesUtility::USER_TYPE_FMA;
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$totype = CodesUtility::USER_TYPE_EXPORTER;
				break;
		}
		
		
		$organizations = new Organizations();
		$orgvalue = $organizations->getOrganizationSupplier($totype,array(0=>'org_id',1=>'name'));
		
		$this->assign("supplier",$orgvalue);
		$this->assign("country",$countryValue);
		$this->assign("blanketpo",$blanketpo);
		$this->assign("orders",$ordersValues);
		$this->setNoLayout();
		$this->render('vieworders.tpl');
		//- end here
	}
	
	public function viewOrdersAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("Countries");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("PageUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$blanketpo = $this->getParam("blanketpo") ? $this->getParam("blanketpo") : 0;
		$search = $this->getParam("search");
		$usersearch = $this->getParam("usersearch");
		$page = $this->getParam("page");
		
		
		
		$auth = BaseAuth::getInstance();
		$orders = new purchaseOrders();
		$ordersValues =$orders->getOrderByOrg($auth->org_id,$blanketpo,$search);
		
		if(!$search) {
		
			$countries = new Countries();
			$countryValue = $countries->getCountries(array(0=>'country_code',1=>'country'));
			
				$auth = BaseAuth::getInstance();
			
				$userTypes = new UserTypes();
				$userTypesArray = $userTypes->getUserTypesArray("id", "code");
				$org_type = $userTypesArray[$auth->user_type_id];
				switch($org_type) {
					case CodesUtility::USER_TYPE_EXPORTER:
						$totype = CodesUtility::USER_TYPE_FMA;
						break;
					case CodesUtility::USER_TYPE_IMPORTER:
						$totype = CodesUtility::USER_TYPE_EXPORTER;
						break;
				}
				
			
			$organizations = new Organizations();
			$orgvalue = $organizations->getOrganizationSupplier($totype,array(0=>'org_id',1=>'name'));
			
			
			
			
			$this->assign("supplier",$orgvalue);
			$this->assign("country",$countryValue);
			$this->assign("blanketpo",$blanketpo);
			
		}
		
		$pagelist = array();
		
		
		$fields['date_order'] = 'Date';
		$fields['po_no'] = 'PO No';
		$fields['supplier'] = 'Supplier';
		$fields['totalAmount'] = 'Amount';
		$fields['status'] = 'Status';
		
		$cart = CartUtility::getToexcelCart();
		$cart->items = $ordersValues;
		$cart->fields = $fields;
		
	
		if($page > 0) {		
			$list = PageUtility::pagination($ordersValues,15,$page);				
		} else {
			$list = PageUtility::pagination($ordersValues,15,0);
		}
		
		$pagelist['pagelength'] = PageUtility::pagelength(10,round(count($ordersValues)/15));
		$pagelist['action'] = "/account/viewOrders/usersearch/1/blanketpo/".$blanketpo;
		$this->assign("pagelist",$pagelist);
		
		$this->assign("orders",$list);
		
		$this->assign("search",$usersearch);
		$this->setNoLayout();
		$this->render('vieworders.tpl');
		
	}
	
	public function viewOrderDetailsAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("Sizes");
		$auth = BaseAuth::getInstance();
		
		$poid = $this->getParam("poid");
		$supplier_org_id = $this->getParam("supplier_org_id");
		
		$size = new Sizes();
		
		$auth = BaseAuth::getInstance();
		$orders = new purchaseOrders();
		$orderValues =$orders->getOrdersDetailsByOrg($auth->org_id,$poid,$supplier_org_id);
		$sizeValues = $size->getSize();
		
		$po_no = $orderValues[$supplier_org_id]['po_no'];

		//echo "<pre>";print_r($orderValues);echo "</pre>";
		$this->assign("size",$sizeValues);
		$this->assign("poid",$po_no);
		$this->assign("supplier_org_id",$supplier_org_id);
		$this->assign("orders",$orderValues);
		$this->setNoLayout();
		$this->render("vieworderdetails.tpl");
			
	}
	public function resendOrderAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("AccountUtility");
		
		$poid = $this->getParam("poid");
		$supplier_org_id = $this->getParam("supplier_org_id");
		
		
		$auth = BaseAuth::getInstance();
		$orders = new purchaseOrders();
		$orderValues =$orders->getOrdersDetailsByOrg($auth->org_id,$poid,$supplier_org_id);
		$acctUtil = new AccountUtility();
		$acctUtil->saveToPo($orderValues,0,0,1);
		//$this->_redirect("/account/viewOrders/");
		// redirect on live site won't work, i don't know why
		$auth = BaseAuth::getInstance();
		$orders->clear();
		$ordersValues =$orders->getOrderByOrg($auth->org_id,0);
		
		$this->assign("orders",$ordersValues);
		$this->setNoLayout();
		$this->render('vieworders.tpl');
			
	}
	
	public function retrieveSupplierAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		$auth = BaseAuth::getInstance();	
		
		$country_code = $this->getParam("country_code");
		
		$supplier = new purchaseOrders();
		
		$supplierValues = $supplier->getSupplierByOrg($auth->org_id,$country_code);
		$this->assign("suppliers",$supplierValues);
		$this->setNoLayout();
		$this->render("orssupplier.tpl");
	}
	
	public function createorsAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("Countries");

		
		$auth = BaseAuth::getInstance();	
		$supplier = new purchaseOrders();
		
		$supplierValues = $supplier->getSupplierByOrg($auth->org_id);
		$date = getdate();
		
		$countries = new Countries();
		$countries->loadWhere("1 = 1",array("country"));
		
		$this->assign("countries",$countries->toArray());
		$this->assign("date",$date[0]);
		$this->assign("suppliers",$supplierValues);
		$this->setNoLayout();
		$this->render();
	}
	
	public function retrievePoAction(){
		
		Zend_Loader::loadClass("purchaseOrders");	
		
		$supplier_org_id = $this->getParam("supplier_org_id");
		
		$auth = BaseAuth::getInstance();
		
		$po = new purchaseOrders();
		$poValues = array();
		if($supplier_org_id)
			$poValues = $po->getSupplierPoByOrg($auth->org_id,$supplier_org_id);
		$this->setNoLayout();
		$this->assign("polist",$poValues);
		$this->render("ponolist.tpl");
	}
	
	public function retrievepodetailAction(){
		
		Zend_Loader::loadClass("Tanks");
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("AccountUtility");
		
		$auth = BaseAuth::getInstance();
		$tankList = new Tanks();
		$tankList->loadWhere(" org_id = ". $auth->org_id );
		
		$user_type = AccountUtility::getUserType($auth->user_type_id);
		
		$userValue = $this->getParam("user");
		$poid = $userValue['poid'];
		$supplier_org_id = $userValue['supplier_org_id'];
		
		$podetailValues = array();
		if($poid) {
			$podetail = new purchaseOrders();
			$podetailValues = $podetail->getOrdersDetailsByOrg($auth->org_id,$poid,$supplier_org_id,1,1);
		
		}
		$this->setNoLayout();
		$this->assign("supplier_org_id",$supplier_org_id);
		$this->assign("user_type",$user_type);
		$this->assign("tanklists",$tankList->toArray());
		$this->assign("podetails",$podetailValues);
		$this->render('podetails.tpl');
	}
	
	public function selectReasonAction(){
		Zend_Loader::loadClass("RejectReasons");	
		Zend_Loader::loadClass("CartUtility");
		
		
		$cart = CartUtility::getReasonCart();
		$items = $cart->items;
		//print_r($items);
		$qty = $this->getParam('qty');
		$id = $this->getParam('id');
		
		
		$reasonList = new RejectReasons();
		$reasonList->loadWhere("1=1","reason");
		
		$this->assign("items",$items[$id]);
		$this->assign("id",$id);
		$this->assign("qty",$qty);
		$this->assign("reasonList",$reasonList->toArray());
		$this->setNoLayout();
		$this->render('selectreason.tpl');
	}
	
	public function saveReasonAction(){
		
		Zend_Loader::loadClass("CartUtility");
		
		$id = $this->getParam("id");
		$cart = CartUtility::getReasonCart();
		$items = $cart->items;
		
		$reason = $this->getParam('reason');
		$items[$id] = array();
		foreach($reason as $key => $value) {
			$items[$id][$key] = $value;
		}
		
		$cart->items = $items;
		//print_r($items);
	}

	public function orgOrganismLookupAction() {
			
		Zend_Loader::loadClass("EcoezUtility");
		$auth = BaseAuth::getInstance();
		
		$userValue = $this->getParam("user");
		// moid
//		if(!isset($userValue["moid"])) {
//			Zend_Loader::loadClass("Organisms");
//			$organism = new Organisms();
//			$moidList = $organism->getMOIDByOrgId($auth->org_id);
//			$this->assign('moids',$moidList);
//		}
		// organism groups
		//if(!isset($userValue["organismGroup"])) {
			Zend_Loader::loadClass("OrganismGroups");
			$group = new OrganismGroups();
			$groupList = $group->getOrganismGroupsByOrgId($auth->org_id);
			$this->assign('organismGroups',$groupList);
		//}

		$searchStatus = $userValue["filter"];
		//$searchMOID = $userValue["moid"];
		$searchGroup = $userValue["organismGroup"];
		$searchName = $userValue["searchName"];
		$searchAlpha = $userValue["alpha"];
		$reload = $this->getParam("reload");

		//echo $orderingStatus;die();
		$organisms = new EcoezUtility();
		$organismValues = $organisms->getOrganismsByOrgId($auth->org_id,$searchStatus,$searchGroup,$searchName,$searchAlpha,"1");
		//$organismValues = $organisms->getOrganismsByOrgId($auth->org_id,$searchStatus,$searchMOID,$searchGroup,$searchName,$searchAlpha,$reload);

		// cart
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getToexcelCart();
		$cart->result = $organismValues;

		$this->setNoLayout();
		$this->assign("orgOrganisms",$organismValues);
		
		if ($reload == '1') {
			$this->render('orgorganismlist.tpl');
		}
		else {
			$this->render('organism.tpl');
		}
	}
	
	public function saveOrganismLookupAction() {
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$excelwriter = new ExcelWriter();
		$filename = mt_rand();
		$excelwriter->ExcelWriter($filename.".xls");

		$cart = CartUtility::getToexcelCart();
		$result = $cart->result;

		//echo $result;die();
		
		// headers
		$header[] = 'Name';
		$header[] = 'Ordering Status';
		$header[] = 'Last Buy';
		$header[] = 'Last Sale';
		$header[] = 'Base Price';
		$header[] = 'Reorder';
		$header[] = 'Default Supplier';
		$header[] = 'Min Order';
		$excelwriter->writeLine($header);

		foreach($result as $key => $value) {

			$line = array();
			$line = $value['name'];
			$line = $value['ordering_status'];
			$line = $value['last_buy'];
			$line = $value['last_sale'];
			$line = $value['currency_mark'].' '.$value['base_price_sale'];
			$line = $value['reorder_level'];
			$line = $value['supplier_name'];
			$line = $value['min_order'];
			
			$excelwriter->writeLine($line);
		}

		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->setNoLayout();
		$this->assign("filename",$filename.".xls");
		$this->render("downloadfile.tpl");

	}

	public function orgDAAReportAction() {
	
		Zend_Loader::loadClass("InventoryDAAs");
		$auth = BaseAuth::getInstance();
		
		// tanks
		if(!isset($userValue["tank"])) {
			Zend_Loader::loadClass("Tanks");
			$tankList = new Tanks();
			$tankList->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('orgTanks',$tankList->toArray());
		}
		// moid
		if(!isset($userValue["moid"])) {
			Zend_Loader::loadClass("Organisms");
			$organism = new Organisms();
			$moidList = $organism->getMOIDByOrgId($auth->org_id);
			$this->assign('moids',$moidList);
		}
		// sizes
		if(!isset($userValue["size_code"])) {
			Zend_Loader::loadClass("Sizes");
			$size = new Sizes();
			$size->loadWhere (" 1 = 1");
			$this->assign('sizeCodes',$size->toArray());
		}
		
		// user values
		$userValue = $this->getParam("user");
		$searchTank = $userValue["tank"];
		$searchMOID = $userValue["moid"];
		$searchSizeCode = $userValue["size_code"];
		$searchDateFrom = $userValue["date_mortality_from"];
		$searchDateTo = $userValue["date_mortality_to"];
		
		$daas = new InventoryDAAs();
		$daasList = $daas->getOrgDAAReportByOrgId($auth->org_id,$searchTank,$searchMOID,$searchSizeCode,$searchDateFrom,$searchDateTo);
		
		// cart
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getToexcelCart();
		$cart->result = $daasList;

		$this->setNoLayout();
		$this->assign("daasList",$daasList);
				
		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('daasReportList.tpl');
		}
		else {
			$this->render('daasReport.tpl');
		}
	}
	
	public function saveOrgDAAReportAction() {
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$excelwriter = new ExcelWriter();
		$filename = mt_rand();
		$excelwriter->ExcelWriter($filename.".xls");

		$cart = CartUtility::getToexcelCart();
		$result = $cart->result;

		// headers
		$header[] = 'Tank';
		$header[] = 'MOID';
		$header[] = 'Common Name';
		$header[] = 'Size';
		$header[] = 'DAA Qty';
		$header[] = 'DAA Amt';
		$header[] = 'Mortality Date';
		$header[] = 'Reason';

		$excelwriter->writeLine($header);

		foreach($result as $key => $value) {

			$line = array();
			$line = $value['tank_name'];
			$line = $value['moid'];
			$line = $value['common_name'];
			$line = $value['size'];
			$line = $value['quantity_daa'];
			$line = $value['currency_mark'].' '.$value['stock_amount'];
			$line = $value['date_mortality'];
			$line = $value['remark'];

			$excelwriter->writeLine($line);
		}

		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->setNoLayout();
		$this->assign("filename",$filename.".xls");
		$this->render("downloadfile.tpl");

	}

	public function orgDOAReportAction() {
	
		Zend_Loader::loadClass("Receipts");
		$auth = BaseAuth::getInstance();

		// tanks
		if(!isset($userValue["tank"])) {
			Zend_Loader::loadClass("Tanks");
			$tankList = new Tanks();
			$tankList->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('orgTanks',$tankList->toArray());
		}
		// moid
		if(!isset($userValue["moid"])) {
			Zend_Loader::loadClass("Organisms");
			$organism = new Organisms();
			$moidList = $organism->getMOIDByOrgId($auth->org_id);
			$this->assign('moids',$moidList);
		}
		// suppliers
		if(!isset($userValue["supplier_org_id"])) {
			$supplier = new Receipts();
			$supplierList = $supplier->getReceiptSupplierByOrgId($auth->org_id);
			$this->assign('ordSupplier',$supplierList);
		}
		
		
		// user values
		$userValue = $this->getParam("user");
		$searchSupplier = $userValue["supplier_org_id"];
		$searchTank = $userValue["tank"];
		$searchMOID = $userValue["moid"];
		$searchDateFrom = $userValue["date_receive_from"];
		$searchDateTo = $userValue["date_receive_to"];
		$searchPO = $userValue["search_po"];
		$groupBy = $userValue["group"];
		
		if (!$groupBy) { $groupBy = '0'; }

		$doa = new Receipts();
		$doaList = $doa->getReceiptDOAByOrgId($auth->org_id,$searchSupplier,$searchTank,$searchMOID,$searchDateFrom,$searchDateTo,$searchPO,$groupBy);
		
		// cart
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getToexcelCart();
		$cart->result = $doaList;
		$cart->group = $groupBy;

		$this->setNoLayout();
		$this->assign("group",$groupBy);
		$this->assign("doaList",$doaList);

		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('doaReportList.tpl');
		}
		else {
			$this->render('doaReport.tpl');
		}
	}
	
	public function saveOrgDOAReportAction() {
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$excelwriter = new ExcelWriter();
		$filename = mt_rand();
		$excelwriter->ExcelWriter($filename.".xls");

		$cart = CartUtility::getToexcelCart();
		$result = $cart->result;
		$group = $cart->group;

		//echo $group;die();
		// headers
		if ($group == '0' || $group == "") {
			$header[] = 'Date Received';
			$header[] = 'PO No';
			$header[] = 'MOID';
			$header[] = 'Common Name';
			$header[] = 'Supplier Name';
			$header[] = 'Country';
			$header[] = 'Tank';
			$header[] = 'Received Qty';
			$header[] = 'DOA Qty';
		}
		if ($group == '1') {
			$header[] = 'First Received';
			$header[] = 'Last Received';
			$header[] = 'Supplier Name';
			$header[] = 'Country';
			$header[] = 'Issued POs';
			$header[] = 'MOID';
			$header[] = 'Tank';
			$header[] = 'Total Received Qty';
			$header[] = 'Total DOA Qty';
		}
		if ($group == '2') {
			$header[] = 'First Received';
			$header[] = 'Last Received';
			$header[] = 'MOID';
			$header[] = 'Issued POs';
			$header[] = 'Supplier Name';
			$header[] = 'Tank';
			$header[] = 'Total Received Qty';
			$header[] = 'Total DOA Qty';
		}
		if ($group == '3') {
			$header[] = 'First Received';
			$header[] = 'Last Received';
			$header[] = 'Tank';
			$header[] = 'Issued POs';
			$header[] = 'MOID';
			$header[] = 'Supplier Name';
			$header[] = 'Total Received Qty';
			$header[] = 'Total DOA Qty';
		}

		$excelwriter->writeLine($header);

		if ($group == '0' || $group == '') {
			foreach($result as $key => $value) {
				$line = array();
				$line = $value['date_receipt'];
				$line = $value['po_no'];
				$line = $value['moid'];
				$line = $value['specie'];
				$line = $value['supplier_name'];
				$line = $value['country'];
				$line = $value['tank_name'];
				$line = $value['received_quantity'];
				$line = $value['doa_quantity'];
				$excelwriter->writeLine($line);
			}
		}

		if ($group == '1') {
			foreach($result as $key => $value) {
				$line = array();
				$line = $value['first_receipt'];
				$line = $value['last_receipt'];
				$line = $value['supplier_name'];
				$line = $value['country'];
				$line = $value['count_po_no'];
				$line = $value['count_moid'];
				$line = $value['count_tank'];
				$line = $value['sum_received_quantity'];
				$line = $value['sum_doa_quantity'];
				$excelwriter->writeLine($line);
			}
		}

		if ($group == '2') {
			foreach($result as $key => $value) {
				$line = array();
				$line = $value['first_receipt'];
				$line = $value['last_receipt'];
				$line = $value['moid'];
				$line = $value['count_po_no'];
				$line = $value['count_supplier'];
				$line = $value['count_tank'];
				$line = $value['sum_received_quantity'];
				$line = $value['sum_doa_quantity'];
				$excelwriter->writeLine($line);
			}
		}

		if ($group == '3') {
			foreach($result as $key => $value) {
				$line = array();
				$line = $value['first_receipt'];
				$line = $value['last_receipt'];
				$line = $value['tank_name'];
				$line = $value['count_po_no'];
				$line = $value['count_moid'];
				$line = $value['count_supplier'];
				$line = $value['sum_received_quantity'];
				$line = $value['sum_doa_quantity'];
				$excelwriter->writeLine($line);
			}
		}

		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->setNoLayout();
		$this->assign("filename",$filename.".xls");
		$this->render("downloadfile.tpl");

	}

	public function orgInvRejectReportAction() {
	
		Zend_Loader::loadClass("InventoryRejects");
		$auth = BaseAuth::getInstance();
		
		// tanks
		if(!isset($userValue["tank"])) {
			Zend_Loader::loadClass("Tanks");
			$tankList = new Tanks();
			$tankList->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('orgTanks',$tankList->toArray());
		}
		// moid
		if(!isset($userValue["moid"])) {
			Zend_Loader::loadClass("Organisms");
			$organism = new Organisms();
			$moidList = $organism->getMOIDByOrgId($auth->org_id);
			$this->assign('moids',$moidList);
		}
		// reject reason
		if(!isset($userValue["rejectReason"])) {
			Zend_Loader::loadClass("RejectReasons");
			$rejectList = new RejectReasons();
			$rejectList->loadWhere(" 1=1 ");
			$this->assign('rejectReasons',$rejectList->toArray());
		}
		
		// user values
		$userValue = $this->getParam("user");
		$searchTank = $userValue["tank"];
		$searchMOID = $userValue["moid"];
		$searchReject = $userValue["reject_reason"];
		$searchDateFrom = $userValue["reject_date_from"];
		$searchDateTo = $userValue["reject_date_to"];
		$searchTransType = $userValue["transaction_source"];
		
		// echo "<pre>";print_r($searchTank);echo "</pre>";
		
		$reject = new InventoryRejects();
		$rejectList = $reject->getOrgInvRejectsByOrgId($auth->org_id,$searchTank,$searchMOID,$searchReject,$searchDateFrom,$searchDateTo,$searchTransType);
		
		// cart
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getToexcelCart();
		$cart->result = $rejectList;


		$this->setNoLayout();
		$this->assign("rejectList",$rejectList);
		
		$reload = $this->getParam("reload");
		if ($reload == '1'){
			$this->render('invRejectReportSub.tpl');
		}
		else {
			$this->render('invRejectReport.tpl');
		}
	}
	
	public function saveOrgInvRejectReportAction() {
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$excelwriter = new ExcelWriter();
		$filename = mt_rand();
		$excelwriter->ExcelWriter($filename.".xls");

		$cart = CartUtility::getToexcelCart();
		$result = $cart->result;

		// headers
		$header[] = 'Tank';
		$header[] = 'MOID';
		$header[] = 'Common Name';
		$header[] = 'Size';
		$header[] = 'Reason';
		$header[] = 'Transactions';
		$header[] = 'Date Reject';
		$header[] = 'Quantity';
		$header[] = 'Reject Amt.';

		$excelwriter->writeLine($header);

		foreach($result as $key => $value) {

			$line = array();
			$line = $value['tank_name'];
			$line = $value['moid'];
			$line = $value['name'];
			$line = $value['size'];
			$line = $value['reason'];
			$line = $value['last_transaction_source'];
			$line = $value['reject_date'];
			$line = $value['quantity'];
			$line = $value['currency_mark'].' '.$value['amount'];

			$excelwriter->writeLine($line);
		}

		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->setNoLayout();
		$this->assign("filename",$filename.".xls");
		$this->render("downloadfile.tpl");

	}

	public function orgInventoryAction() {
		
		Zend_Loader::loadClass("Inventories");
		$auth = BaseAuth::getInstance();
		
		$userValue = $this->getParam("user");
		
		// tanks
		if(!isset($userValue["tank"])) {
			Zend_Loader::loadClass("Tanks");
			$tankList = new Tanks();
			$tankList->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('orgTanks',$tankList->toArray());
		}
		// moid
		if(!isset($userValue["moid"])) {
			Zend_Loader::loadClass("Organisms");
			$organism = new Organisms();
			$moidList = $organism->getMOIDByOrgId($auth->org_id);
			$this->assign('moids',$moidList);
		}
		// organism groups
		if(!isset($userValue["organismGroup"])) {
			Zend_Loader::loadClass("OrganismGroups");
			$group = new OrganismGroups();
			$groupList = $group->getOrganismGroupsByOrgId($auth->org_id);
			$this->assign('organismGroups',$groupList);
		}
				
		// user values
		$searchTank = $userValue["tank"];
		$searchMOID = $userValue["moid"];
		$searchGroup = $userValue["organismGroup"];
		$searchFilter = $userValue["otherFilter"];
		$searchName = $userValue["searchName"];
		$searchAlpha = $userValue["alpha"];
		$reload = $this->getParam("reload");

		// inventories
		$inventory = new Inventories();
		$inventoryValues = $inventory->getOrgInventoryByOrgId($auth->org_id,$searchTank,$searchMOID,$searchGroup,$searchFilter,$searchName,'',$searchAlpha,$reload);
		
		// cart
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getToexcelCart();
		$cart->result = $inventoryValues;
		
		$this->setNoLayout();
		$this->assign("orgInventory",$inventoryValues);
		//$this->render('orgInventory.tpl');
		
		if ($reload == '1') {
			$this->render('orgInventoryList.tpl');
		}
		else {
			$this->render('orgInventory.tpl');
		}
	}
	
	public function saveOrgInventoryAction() {
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$excelwriter = new ExcelWriter();
		$filename = mt_rand();
		$excelwriter->ExcelWriter($filename.".xls");

		$cart = CartUtility::getToexcelCart();
		$result = $cart->result;

		// headers
		$header[] = 'Tank';
		$header[] = 'MOID';
		$header[] = 'Group';
		$header[] = 'Common Name';
		$header[] = 'Size';
		$header[] = 'On-Hand';
		$header[] = 'On-Shipment';
		$header[] = 'Stock Amt.';
		$header[] = 'MAC Cert';
		$header[] = 'DAA';
		$header[] = 'Last DAA';

		$excelwriter->writeLine($header);

		foreach($result as $key => $value) {

			$line = array();
			$line = $value['tank_name'];
			$line = $value['moid'];
			$line = $value['organism_group'];
			$line = $value['common_name'];
			$line = $value['size'];
			$line = $value['total_qty_on_hand'];
			$line = $value['total_qty_on_shipment'];
			$line = $value['currency_mark'].' '.$value['total_stock_amount'];
			$line = $value['mac_certified'];
			$line = $value['quantity_daa'];
			$line = $value['date_mortality'];

			$excelwriter->writeLine($line);
		}

		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->setNoLayout();
		$this->assign("filename",$filename.".xls");
		$this->render("downloadfile.tpl");

	}

	public function FMAListAction() {
		
		Zend_Loader::loadClass("FishingAreas");
		
		$userValue = $this->getParam("user");

		// country
		if(!isset($userValue["country"])) {
			Zend_Loader::loadClass("Countries");
			$countryList = new Countries();
			$countryList->loadWhere(" 1 = 1 ");
			$this->assign('countries',$countryList->toArray());
		}

		// user values
		$searchCountry = $userValue["country"];
		$searchStatus = $userValue["status"];
		$searchMAC = $userValue["mac"];
		$searchFilter = $userValue["filter"];

		// fishing areas
		$fma = new FishingAreas();
		$fmaList = $fma->getFMAList($searchCountry,$searchStatus,$searchMAC,$searchFilter);

		$this->setNoLayout();
		$this->assign("fmaList",$fmaList);
		
		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('fmaListSub.tpl');
		}
		else {
			$this->render('fmaList.tpl');
		}
	}
	
	public function editAddressAction(){
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Country");
		// echo "<pre>test</pre>";
		
		$auth = BaseAuth::getInstance();
		$addressId = $this->getParam("addressId");
		$addressType = $this->getParam("addressType");
		
		$organization = new Organization();
		$orgValues = $organization->getAddressByOrgId($auth->org_id,$addressType,$addressId);
		
		$country = new Country();
		$countryNames = $country->getCountryNames();
		
		// $this->setLayout("accounts-inner.tpl");
		$this->setNoLayout();
		$this->assign("address",$orgValues);
		$this->assign("countries",$countryNames);
		$this->render("editaddress.tpl");
	}

	public function getStaffAddressAction(){
		
		Zend_Loader::loadClass("Addresses");
		Zend_Loader::loadClass("Country");

		$auth = BaseAuth::getInstance();
		$addressId = $this->getParam("addressId");
		$staffView = $this->getParam("staffView");
		
		// staff address
		$address = new Addresses();
		$addressData = $address->getAddress($addressId);
		
		// country
		$country = new Country();
		$countryNames = $country->getCountryNames();
		
		$this->setNoLayout();
		$this->assign("address",$addressData);
		$this->assign("countries",$countryNames);
		$this->assign("staffView",1);
		$this->render("editaddress.tpl");

	}

	public function getStaffContactAction(){
		
		Zend_Loader::loadClass("Contacts");
		
		$auth = BaseAuth::getInstance();
		$contactId = $this->getParam("contactId");
		
		$contact = new Contacts();
		$contactData = $contact->getContact($contactId);
		
		// echo "<pre>";print_r($contactId);echo "</pre>";
		
		$this->setNoLayout();
		$this->assign("contact",$contactData);
		$this->assign("staffView",1);
		$this->render("editcontact.tpl");
	}
	
	public function editInventoryDAALineAction(){
		Zend_Loader::loadClass("InventoryDAA");
		Zend_Loader::loadClass("Currencies");
		
		$auth = BaseAuth::getInstance();
		
		$invId = $this->getParam("inventoryId");
		$invDAAId = $this->getParam("inventoryDAAId");
		// echo "<pre>";print_r($invId);echo "</pre>";
		$invDAA = new InventoryDAA();
		$invDAAValues = $invDAA->getInventoryDAALineByInvId($invId,$invDAAId);
		
		// currencies
		$currencies = new Currencies();
		$currenciesValues = $currencies->getCurrencies();
		// load the following data if this is a NEW entry
		if(!$invId || $invId == 0) {
			// inventory source
			Zend_Loader::loadClass("Inventories");
			$inventory = new Inventories();
			$sourceList = $inventory->getOrgInvSelectionByOrgId($auth->org_id);
			$this->assign('sources',$sourceList);
		}
		// echo "<pre>";print_r($invId);echo "</pre>";die();
		// $this->setLayout("accounts-inner.tpl");
		$this->setNoLayout();
		$this->assign("currencies",$currenciesValues);
		$this->assign("daas",$invDAAValues);
		$this->assign("invId",$invId);
		$this->render("editInventoryDAA.tpl");
			
	}

	public function editContactAction(){
		Zend_Loader::loadClass("Organization");
		
		$auth = BaseAuth::getInstance();
		$contactId = $this->getParam("contactId");
		
		$organization = new Organization();
		$orgValues = $organization->getContactByOrgId($auth->org_id,$contactId);
		
		//echo "<pre>";print_r($orgValues);echo "</pre>";
		
		$this->setNoLayout();
		$this->assign("contact",$orgValues);
		$this->render("editcontact.tpl");
	}
	
	public function editPaymentInformationAction(){
		Zend_Loader::loadClass("OrganizationPaymentInformation");
		Zend_Loader::loadClass("Organization");
		
		$auth = BaseAuth::getInstance();
		$paymentId = $this->getParam("paymentId");
		
		$paymentInformation = new Organization();
		$paymentValues = $paymentInformation->getPaymentInformationByOrgId($auth->org_id, $paymentId);
		//echo "<pre>";print_r($orgValues);echo "</pre>";
		
		$this->setNoLayout();
		$this->assign("paymentInformation",$paymentValues);
		$this->render("editpayment.tpl");
	}
	
	public function getInventoryDAAAction() {
		
		Zend_Loader::loadClass("InventoryDAAs");
		
		$invId = $this->getParam("inventoryId");
		$tankName = $this->getParam("tankName");
		$moid = $this->getParam("moid");

		if (isset($invId) && $invId) {
			$invDAA = new InventoryDAAs();
			$daas = $invDAA->getOrgInventoryDAAByInvId($invId);
			$this->setLayout("accounts-inner.tpl");
			$this->assign("daasList",$daas);
			$this->assign("tank_name",$tankName);
			$this->assign("moid",$moid);
			$this->assign("invId",$invId);
			$this->render("daasList.tpl");		
		}
	}

	public function saveInventoryDAAAction() {
		
		Zend_Loader::loadClass("InventoryDAA");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		
		$invDAA = new InventoryDAA();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if (isset($userValue['inv_daa_id']) && $userValue['inv_daa_id']) {
			$defaultValue = $userValue['inv_daa_id'];	
		}
		
		$invDAA->loadWhere(" inventory_daa_id = " . $defaultValue);
		
		if (isset($userValue['inv_id']) && $userValue['inv_id'] > 0) {
			$invDAA->inventory_id = $userValue["inv_id"];
		}
		else {
			$invDAA->inventory_id = $userValue["inventory_id"];			
		}
		$invDAA->quantity_daa = $userValue["quantity_daa"];
		$invDAA->date_mortality = $userValue["date_mortality"];
		$invDAA->currency_mark = $userValue["currency_mark"];
		$invDAA->stock_amount = $userValue["stock_amount"];
		$invDAA->reason = $userValue["reason"];
		
		if(!$invDAA->inventory_daa_id) {
			$invDAA->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$invDAA->created_by = $auth->id;
		}
		$invDAA->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$invDAA->updated_by = $auth->id;
		
		if ($userValue['inv_id'] > 0 || $userValue['inventory_id'] > 0) {
			$invDAA->save();
		}
		
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/orgDAAReport')");
		$this->render("empty.tpl");
		
	}
	
	public function saveAddressAction() {
		
		Zend_Loader::loadClass("Address");
		Zend_Loader::loadClass("OrganizationAddress");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		
		$address = new Address();
		$orgAddress = new OrganizationAddress();
		$userValue = $this->getParam("user");
		
		//address
		//echo $userValue['address_id'];die();
		//print_r($userValue);die();
		$defaultvalue = 0;
		if (isset($userValue['address_id']) && $userValue['address_id']) {
			$defaultvalue = $userValue['address_id'];
		}
		// echo $defaultvalue;die();
		
		$address->loadWhere("address_id = ". $defaultvalue);
		
		$address->address1 = $userValue["address1"];
		$address->address2 = $userValue["address2"];
		$address->city = $userValue["city"];
		$address->province = $userValue["province"];
		$address->country_code = $userValue["country_code"];
		$address->zip = $userValue["zip"];
		if(!$address->address_id) {
			$address->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$address->created_by = $auth->id;
		}
		$address->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$address->updated_by = $auth->id;
		$address->save();
		
		//org address
		$defaultOrgAddress = 0;
		if (isset($userValue['org_address_id']) && $userValue['org_address_id']) {
			$defaultOrgAddress = $userValue['org_address_id'];
		}
		//echo $defaultOrgAddress;die();
		$orgAddress->loadWhere(" org_address_id = ". $defaultOrgAddress);
		$orgAddress->org_id = $auth->org_id;
		$orgAddress->address_id = $address->address_id;
		$orgAddress->address_type = $userValue["address_type"];
		$orgAddress->save();
		$orgAddress->org_address_id = $orgAddress->id;
		$orgAddress->save();
		
		//echo $userValue['primary_address'];die();
		//save as primary address
		if (isset($userValue["primary_address"]) &&  $userValue["primary_address"] == 'on')
		{
			$org = new Organization();
			$org->loadWhere(" org_id = ". $auth->org_id);
			/*$org->primary_address_id = $userValue["org_address_id"];*/
			$org->primary_address_id = $orgAddress->org_address_id;
			$org->save();
		}
				
		$this->setLayout("ajax.tpl");
		if($userValue["staff_view"] == 1) {
			$this->assign("function","changeTabView('/account/orgStaffs')");
		} else {
			$this->assign("function","changeTabView('/account/adminProfile')");	
		}
		$this->render("empty.tpl");
	}

	public function savePaymentInformationAction() {
		Zend_Loader::loadClass("OrganizationPaymentInformation");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		
		$paymentInformation = new OrganizationPaymentInformation();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if (isset($userValue['payment_id']) && $userValue['payment_id']) 
		{
			$defaultValue = $userValue['payment_id'];
		}
		
		$paymentInformation->loadWhere(" id = ". $defaultValue);
		$paymentInformation->org_id = $auth->org_id;
		$paymentInformation->title = $userValue["title"];
		$paymentInformation->content = $userValue["content"];
		if (isset($userValue["default_payment"]) && $userValue["default_payment"] == 'on') {		
			$paymentInformation->is_active = 1;
		}
		$paymentInformation->save();
		
		$this->setLayout("ajax.tpl");
		if($userValue["staff_view"] == 1) {
			$this->assign("function","changeTabView('/account/orgStaffs')");
		} else {
			$this->assign("function","changeTabView('/account/adminProfile')");
		}
		
		$this->render("empty.tpl");		
	}
	
	public function saveContactAction() {
		
		Zend_Loader::loadClass("Contact");
		Zend_Loader::loadClass("OrganizationContact");
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		
		$contact = new Contact();
		$orgContact = new OrganizationContact();
		$userValue = $this->getParam("user");
		
		//contact 
		$defaultValue = 0;
		if (isset($userValue['contact_id']) && $userValue['contact_id']) 
		{
			$defaultValue = $userValue['contact_id'];
		}
		$contact->loadWhere(" contact_id = ". $defaultValue);
		$contact->name = $userValue["name"];
		$contact->remarks = $userValue["remarks"];
		$contact->telephone_no = $userValue["telephone_no"];
		$contact->fax_no = $userValue["fax_no"];
		$contact->email = $userValue["email"];
		$contact->birth_date = $userValue["birth_date"];
		$contact->license_date = $userValue["license_date"];
		$contact->blood_group = $userValue["blood_group"];
		$contact->height = $userValue["height"];
		if(!$contact->contact_id) {
			$contact->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$contact->created_by = $auth->id;
		}
		$contact->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$contact->updated_by = $auth->id;
		$contact->save();
		
		//org contact
		$defaultOrgContact = 0;
		if (isset($userValue['org_contact_id']) && $userValue['org_contact_id']) 
		{
			$defaultOrgContact = $userValue['org_contact_id'];
		}
		$orgContact->loadWhere(" org_contact_id = ". $defaultOrgContact);
		$orgContact->org_id = $auth->org_id;
		$orgContact->contact_id = $contact->contact_id;
		$orgContact->save();
		$orgContact->org_contact_id = $orgContact->id;
		$orgContact->save();
		
		// save as primary contact
		if (isset($userValue["primary_contact"]) && $userValue["primary_contact"] == 'on')
		{
			$org = new Organization();
			$org->loadWhere(" org_id = ". $auth->org_id);
			$org->primary_contact_id = $orgContact->org_contact_id;
			$org->save();
		}
		
		$this->setLayout("ajax.tpl");
		if($userValue["staff_view"] == 1) {
			$this->assign("function","changeTabView('/account/orgStaffs')");
		} else {
			$this->assign("function","changeTabView('/account/adminProfile')");
		}
		$this->render("empty.tpl");
		
	}
	
	public function saveProfileAction(){
	
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("Address");
		Zend_Loader::loadClass("OrganizationAddress");
		Zend_Loader::loadClass("Contact");
		Zend_Loader::loadClass("OrganizationContact");
		Zend_Loader::loadClass("TimeUtility");
		
		$organization = new Organization();
		$address = new Address();
		$orgAddress = new OrganizationAddress();
		$contact = new Contact();
		$orgContact = new OrganizationContact();
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
	
		//organization
		$organization->loadWhere("org_id = ". $auth->org_id);
		$organization->name = $userValue['name'];
		$organization->trading_name = $userValue['trading_name'];
		$organization->save();
		$organization->org_id = $organization->id;
		$organization->save();
		
		//address
		$address->loadWhere("address_id = ". $userValue['address_id']);
		$address->address1 = $userValue["address1"];
		$address->address2 = $userValue["address2"];
		$address->city = $userValue["city"];
		$address->province = $userValue["province"];
		$address->country = $userValue["country"];
		$address->zip = $userValue["zip"];
		if(!$address->address_id) {
			$address->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/Y H:i:s'));
			$address->created_by = $auth->id;
		}
		$address->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/Y H:i:s'));
		$address->updated_by = $auth->id;
		$address->save();
		
		//org address
		$orgAddress->loadWhere(" org_address_id = ". $userValue['org_address_id']);
		$orgAddress->org_id = $auth->org_id;
		$orgAddress->address_id = $address->address_id;
		$orgAddress->address_type = $user['address_type'];
		$orgAddress->save();
		$orgAddress->org_address_id = $orgAddress->id;
		$orgAddress->save();
		
		//contact 
		$contact->loadWhere(" contact_id = ". $userValue['contact_id']);
		$contact->name = $userValue["name"];
		$contact->remarks = $userValue["remarks"];
		$contact->telephone_no = $userValue["telephone_no"];
		$contact->fax_no = $userValue["fax_no"];
		$contact->email = $userValue["email"];
		$contact->photo_document_id = $userValue["photo_document_id"];
		$contact->fingerprint_document_id = $userValue["fingerprint_document_id"];
		$contact->birth_date = $userValue["birth_date"];
		$contact->license_date = $userValue["license_date"];
		$contact->blood_group = $userValue["blood_group"];
		$contact->height = $userValue["height"];
		if(!$contact->contact_id) {
			$contact->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$contact->created_by = $auth->id;
		}
		$contact->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$contact->updated_by = $auth->id;
		$contact->save();
		
		//org contact
		$orgContact->loadWhere(" org_contact_id = ". $userValue['org_contact_id']);
		$orgContact->org_id = $auth->org_id;
		$orgContact->contact_id = $contact->contact_id;
		$orgContact->save();
		$orgContact->org_contact_id = $orgContact->id;
		$orgContact->save();
		
	}
	
	public function saveorsAction(){
		
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("AccountUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getReasonCart();
		$items = $cart->items;
		
		$auth = BaseAuth::getInstance();
		
		$doa = $this->getParam("doa");
		$reject = $this->getParam("reject");
		$tank = $this->getParam("tank");
		$user = $this->getParam("user");
		$received = $this->getParam("received");
		
		$poid = $user['poid'];
		$supplier_org_id = $user['supplier_org_id'];	
		
		if($poid) {

			$podetail = new purchaseOrders();
			$podetailValues = $podetail->getOrdersDetailsByOrg($auth->org_id,$poid,$supplier_org_id,1);			
			AccountUtility::saveReceipt($podetailValues,$received,$doa,$reject,$tank,$auth->org_id,$auth->id);
			//$this->_redirect("/account/createors/");
			Zend_Loader::loadClass("Receipts");
			Zend_Loader::loadClass("Organizations");
			Zend_Loader::loadClass("UserTypes");
			Zend_Loader::loadClass("CodesUtility");
			
			$searchFlg = $this->getParam("searchFlg");
			$search = $this->getParam("search");
			
			$organizations = new Organizations();
			
			$auth = BaseAuth::getInstance();
			
			$receipts = new Receipts();
			
			$receiptValue = $receipts->getReceipts($auth->org_id,$search);
		
			
			$userTypes = new UserTypes();
			
			$userTypesArray = $userTypes->getUserTypesArray("id", "code");
			$org_type = $userTypesArray[$auth->user_type_id];
			switch($org_type) {
				case CodesUtility::USER_TYPE_EXPORTER:
					$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_FMA);
					break;
				case CodesUtility::USER_TYPE_IMPORTER:
					$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_EXPORTER);
					//$this->assign("countries",$countries->toArray());
					break;
			}
			
			
			//print_r($receiptValue);
			$this->assign("searchFlg",$searchFlg);
			$this->assign("suppliers",$suppliers);
			$this->assign("receipts",$receiptValue);
			$this->setNoLayout();
			$this->render("viewors.tpl");
			// - redirect end here
			
		}
		
		
	 
		
		
	}
	
	public function vieworsAction(){
		
		Zend_Loader::loadClass("Receipts");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("PageUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$searchFlg = $this->getParam("searchFlg");
		$search = $this->getParam("search");
		$page = $this->getParam("page");
		
		$organizations = new Organizations();
		
		$auth = BaseAuth::getInstance();
		
		$receipts = new Receipts();
		
		$fields['date_receipt'] = 'Date';
		$fields['po_no'] = 'PO No';
		$fields['org_name'] = 'Supplier';
		$fields['received_amount'] = 'Amount';
		
		$receiptValue = $receipts->getReceipts($auth->org_id,$search);
		$cart = CartUtility::getToexcelCart();
		$cart->items = $receiptValue;
		$cart->fields = $fields;
		
		if($page > 0) {		
			$list = PageUtility::pagination($receiptValue,15,$page);				
			$pagelist = array();
	
		} else {
			$list = PageUtility::pagination($receiptValue,15,0);
		}
		
		$pagelist['pagelength'] = PageUtility::pagelength(10,round(count($receiptValue)/15));
		$pagelist['action'] = "/account/viewors/searchFlg/1";
		$this->assign("pagelist",$pagelist);
		
		$userTypes = new UserTypes();
		
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_FMA);
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_EXPORTER);
				//$this->assign("countries",$countries->toArray());
				break;
		}
		
		
		//print_r($receiptValue);
		$this->assign("searchFlg",$searchFlg);
		$this->assign("suppliers",$suppliers);
		$this->assign("receipts",$list);
		$this->setNoLayout();
		$this->render();
	}
	
	public function savetoexcelAction(){
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("ReportsUtility");
		
		$view = $this->getParam("view");
		
		$cart = CartUtility::getToexcelCart();
		$items = $cart->items;
		$fields = $cart->fields;
		
		switch($view) {
			case "ors":
				$filename = ReportsUtility::exportoexcelors($items,$fields);
				break;
			case "":
				
		}
		
		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->assign("filename",$filename.".xls");
		$this->setNoLayout();
		$this->render();

	}
	
	
	public function viewReceiptAction(){
		
		Zend_Loader::loadClass("Receipts");
		Zend_Loader::loadClass("ReceiptRejects");
		
		$poid = $this->getParam("poid");
		$supplier_org_id = $this->getParam("supplier_org_id");
		$date = $this->getParam("date");
		
		$receipts = new Receipts();
		$receiptsvalue = $receipts->getReceiptDetails($poid,$supplier_org_id,$date);
		
		//echo "<pre>";print_r($receiptsvalue);echo "</pre>";
		$this->assign("receipts",$receiptsvalue);
		$this->setNoLayout();
		$this->render('receipt.tpl');
	}

	public function skillAction(){
	
		Zend_Loader::loadClass("Skills");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
				
		$skills = new Skills();
		$skills->loadWhere("1 = 1");
		
		$auth = BaseAuth::getInstance();
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
					
		$this->setNoLayout();
		$this->assign("userType",$org_type);
		$this->assign("skills",$skills->toArray());
		$this->render('skill.tpl');
		
	}
	
	public function editSkillAction(){
		
		Zend_Loader::loadClass("Skill");
		
		$skillId = $this->getParam("skillId");
		$skill = new Skill();
		$skillValues = $skill->getSkillById($skillId);
		
		$this->setLayout("accounts-inner.tpl");
		$this->assign("skill",$skillValues);
		$this->render("editskill.tpl");
		
	}
	
	public function saveSkillAction() {
		
		Zend_Loader::loadClass("Skill");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if(isset($userValue['skill_id']) && $userValue['skill_id']){
			$defaultValue = $userValue['skill_id'];
		}
		$skill = new Skill();
		$skill->loadWhere(" skill_id = " . $defaultValue);
		
		$skill->skill = $userValue['skill'];
		
		if(!$skill->inventory_daa_id) {
			$skill->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$skill->created_by = $auth->id;
		}
		$skill->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$skill->updated_by = $auth->id;
		$skill->save();
		$skill->skill_id = $skill->id;
		$skill->save();
		
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/skill')");
		$this->render("empty.tpl");
		
	}
	
	public function orgTrainingAction(){
		
		Zend_Loader::loadClass("Trainings");
		
		$auth = BaseAuth::getInstance();
		
		$training = new Trainings();
		$trainingValues = $training->getTrainingsByOrgId($auth->org_id);
		$this->setNoLayout();
		$this->assign("trainings",$trainingValues);
		$this->render('training.tpl');
		
	}
	
	public function editTrainingAction(){
		
		Zend_Loader::loadClass("Trainings");
		Zend_Loader::loadClass("Skills");
		
		$auth = BaseAuth::getInstance();
		
		$trainingId = $this->getParam("trainingId");
		$training = new Trainings();
		$trainingValues = $training->getTrainingsByOrgId($auth->org_id,$trainingId);
		
		$skills = new Skills();
		$skills->loadWhere("1 = 1");
		
		// $this->setLayout("accounts-inner.tpl");
		$this->setNoLayout();
		$this->assign("training",$trainingValues);
		$this->assign("skills",$skills->toArray());
		$this->render("edittraining.tpl");
		
	}
	
	public function saveTrainingAction() {
		
		Zend_Loader::loadClass("Training");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if(isset($userValue['training_id']) && $userValue['training_id']){
			$defaultValue = $userValue['training_id'];
		}
		$training = new Training();
		$training->loadWhere(" training_id = " . $defaultValue);
		
		$training->org_id = $auth->org_id;
		$training->skill_id = $userValue['skill_id'];
		$training->course_title = $userValue['course_title'];
		$training->trainor = $userValue['trainor'];
		$training->date_training = $userValue['date_training'];
		
		if(!$training->training_id) {
			$training->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$training->created_by = $auth->id;
		}
		$training->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$training->updated_by = $auth->id;
		$training->save();
		$training->training_id = $training->id;
		$training->save();
		
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/orgTraining')");
		$this->render("empty.tpl");
		
	}
	
	public function dispatchOrderAction(){
	
		//get the customer on purchase order
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		
		$auth = $auth = BaseAuth::getInstance();
		
		//$customer = new purchaseOrders();
		//$customerValues = $customer->getCustomerByOrg($auth->org_id);
		
		$date = getDate();
		//print_r($date);
		
		$customer = new Organizations();
		
		$userTypes = new UserTypes();
		
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
			
				$customer = new purchaseOrders();
				$customerValues = $customer->getCustomerByOrg($auth->org_id);
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$customerValues = $customer->getOrganizationSupplier(CodesUtility::USER_TYPE_IMPORTER_CUSTOMER,array(0=>'name as supplier',1=>'org_id'));
				break;
		}	
		$this->assign("usertype",$org_type);
		$this->assign("date",$date[0]);
		$this->assign("customers",$customerValues);
		$this->setNoLayout();
		$this->render("dispatchorder.tpl");
	}

	public function dispatchpoheadAction(){
	
		Zend_Loader::loadClass("purchaseOrder");
		Zend_Loader::loadClass("Shipmethods");
		
		$purchaseorder = new purchaseOrder();
		$shipmethod = new Shipmethods();
		
		$auth = $auth = BaseAuth::getInstance();
		
		$search = $this->getParam("search");
		$org_id = $search['customer'];
		$poid = $search['pono'];
		if($poid) {
			$purchaseorderValue = $purchaseorder->getPurchaseOrder($org_id,$poid,$auth->org_id);
		
		} else {
			Zend_Loader::loadClass("Organization");
			$organization = new Organization();
			$organization->loadWhere("org_id = ". $search['customer']);
			$orgvalue = $organization->toArray();
			$purchaseorderValue[] = array('name'=>$orgvalue['name']);
			
		}
		$shipmethod->load();
		$date = getDate();
		$this->assign("shipmethod",$shipmethod->toArray());
		$this->assign("date",$date[0]);
		$this->assign("orders",$purchaseorderValue);
		$this->setNoLayout();
		$this->render('dispatchorderhead.tpl');
	
	}
	
	public function dispatchpodetailAction(){
	
		Zend_Loader::loadClass("purchaseOrder");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getDispatchPoCart();
		$items = $cart->items;
		
		$purchaseorder = new purchaseOrder();
		
		$auth = $auth = BaseAuth::getInstance();
		
		$search = $this->getParam("search");
		$org_id = $auth->org_id; //$search['customer'];
		$poid = $search['pono'];
				
		if($poid) {
			$purchaseorderValue = $purchaseorder->getPurchaseOrder($org_id,$poid,$auth->org_id);
			$cart->items = $purchaseorderValue[0]['details'];
		} else {
			$purchaseorderValue = array();
			$cart->items = array();
		}
		
		$this->assign("poid",$poid);
		$this->assign("customerId",$org_id);
		$this->assign("orders",$purchaseorderValue);
		
		$this->setNoLayout();
		$this->render('dispatchorderdetail.tpl');
	}
	
	public function getCustomerPoAction() 
	{
	
		Zend_Loader::loadClass("purchaseOrders");
		$auth = $auth = BaseAuth::getInstance();
		
		$customerId = $this->getParam("customerId");
		$customer = new purchaseOrders();
		$poValues = $customer->getCustomerPoByOrg($auth->org_id,$customerId);
				
		$this->setNoLayout();
		$this->assign("po",$poValues);
		$this->render("customerpo.tpl");
		
	}

	
	public function tankinventoryAction() {
		
		Zend_Loader::loadClass("Inventories");
		Zend_Loader::loadClass("purchaseOrderDetails");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getDispatchCart();
		$items = $cart->items;
		//print_r($items);
		$auth = $auth = BaseAuth::getInstance();
		
		$poid = $this->getParam("poid");
		$customerId = $this->getParam("customerId");
		$moids = $this->getParam("moid");
		$sizecode = $this->getParam("sizecode");
		
		//get the list of moid in order of customer
		//$purchaseItem = new purchaseOrderDetails();
		//$moids = $purchaseItem->getPodetail($auth->org_id,$poid,$customerId,array(0=>'moid'));
		//print_r($moids);die();
		//echo $auth->org_id;die();
//		print $sizecode;
//		print $moids;
//		print $auth->org_id;
//		die();
		$inventory = new Inventories();
		$inventories = $inventory->getOrgInventoryByOrgId($auth->org_id,"",$moids,"","","",$sizecode,"","0");
		
		//echo "<pre>";print_r($inventories);echo "</pre>";
		$this->assign("poid",$this->getParam("poid"));
		$this->assign("customerId",$this->getParam("customerId"));
		$this->assign("dispatch",$items);
		$this->assign("inventories",$inventories);
		$this->setNoLayout();
		$this->render();
	}

	public function updateDispatchAction() {
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AccountUtility");
		
		$qty = $this->getParam("qty");
		
		$pocart = CartUtility::getDispatchPoCart();
		$pitems = $pocart->items;
		
		$cart = CartUtility::getDispatchCart();
		$items = $cart->items;
		
		$newitems = AccountUtility::updateDispatch($qty);
		
		$cart->items = $newitems;
		
		foreach($pitems as $key => $value) {
			
			
			$totalAmount = 0;
			$totalQty = 0;
			foreach($newitems as $pokey => $povalue) {
				$keyArray = explode("_",$pokey);
				if($value['moid'] == $keyArray[1] && $value['size_code'] == $keyArray[2] ) {		
					$totalAmount = $totalAmount + ($povalue * $value['order_amount']);
					$totalQty = $totalQty + $povalue;
				}
			}
			$pitems[$key]['qtydispatch'] = $totalQty;
			$pitems[$key]['totalAmount'] = $totalAmount;
		}
		
		$pocart->items = $pitems;
		
		//print_r($pitems);
		$this->assign("poid",$this->getParam("poid"));
		$this->assign("customerId",$this->getParam("customerId"));
		$this->setNoLayout();
		$array[0]['details']  = $pitems;
		$this->assign("orders",$array);
		$this->render('dispatchorderdetail.tpl');
		
		
		
		
	}
	
	public function viewDispatchOrderAction(){
	
		Zend_Loader::loadClass("Shipments");
		Zend_Loader::loadClass("Countries");
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("PageUtility");	
		Zend_Loader::loadClass("CartUtility");
		
			$countries = new Countries();
			$countryValue = $countries->getCountries(array(0=>'country_code',1=>'country'));
			$auth = $auth = BaseAuth::getInstance();
			$page = $this->getParam("page");
			
			$param = array();
			$usersearch = $this->getParam("usersearch");
			if($usersearch) {
				$this->assign("search",$usersearch);
				$search = $this->getParam("search");
				$param = $search;
			}
			
			$customer = new purchaseOrders();
			$customerValues = $customer->getCustomerByOrg($auth->org_id);
			
			$shipments = new Shipments();
			$shipmentValue =  $shipments->getListOfShipments($auth->org_id,$param);
			
			
		$fields['po_no'] = 'PO Code';
		$fields['name'] = 'Customer';
		$fields['carrier_type'] = 'Carrier Type';
		$fields['carrier_name'] = 'Carrier Name';
		$fields['carrier_code'] = 'Carrier Code';
		$fields['date_shipment'] = 'Dispatch Date';
			
		$cart = CartUtility::getToexcelCart();
		$cart->items = $shipmentValue;
		$cart->fields = $fields;
		
		if($page > 0) {		
			$list = PageUtility::pagination($shipmentValue,15,$page);				
			$pagelist = array();
	
		} else {
			$list = PageUtility::pagination($shipmentValue,15,0);
		}
		
		$pagelist['pagelength'] = PageUtility::pagelength(10,round(count($shipmentValue)/15));
		$pagelist['action'] = "/account/viewDispatchOrder/usersearch/1";
		$this->assign("pagelist",$pagelist);
		
		
		$this->assign("country",$countryValue);
		$this->assign("customers",$customerValues);
		$this->assign("shipments",$list);
		$this->setNoLayout();
		$this->render("listdispatchorder.tpl");
	}
	
	public function viewShipmentDetailsAction(){
		Zend_Loader::loadClass("ShipmentDetails");
		
		$shipment_id = $this->getParam("shipment_id");
		
		$shipmentDetails  = new ShipmentDetails();
		$shipmentValue = $shipmentDetails->getShipmentDetails($shipment_id);
		
		$this->setNoLayout();
		$this->assign("shipmentdetails",$shipmentValue);
		$this->render("shipmentdetails.tpl");
		
	}
	public function savedispatchAction(){
	
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("AccountUtility");
		
		$auth = $auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		$poid = $this->getParam("poid");
		$customerId = $this->getParam("customerId");
		$cart = CartUtility::getDispatchCart();
		$items = $cart->items;
		
		$param = array("poid"=>$poid,"customerId"=>$customerId,'org_id'=>$auth->org_id,'userId'=>$auth->id);
		//print_r($param);die();
		AccountUtility::saveDispatch($items,$userValue,$param);
		$cart->items = null;
		
		$this->_redirect("/account/viewDispatchOrder");
		
	}
	
	public function orgStaffsAction() {
	
		Zend_Loader::loadClass("Staffs");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getAdminCart();
		
		$auth = BaseAuth::getInstance();
		$fromSave = $this->getParam("fromSave");
		// print_r($fromSave);
		if(!$cart->reload || !isset($fromSave)) {
			$userValue = $this->getParam("user");
			$searchIdNo = $userValue["identification_no"];
			$searchStatus = $userValue["status"];
			$searchPosition = $userValue["position"];
			$searchName = $userValue["search_name"];
		} else {
			$userValue = array();
			$searchIdNo = '';
			$searchStatus = '';
			$searchPosition = '';
			$searchName = '';
		}
		$staffs = new Staffs();

		// identification_no
/*		if(!isset($userValue["identification_no"]) && $userValue["identification_no"] <> '' ) {
			Zend_Loader::loadClass("Staffs");
			$ids = new Staffs();
			$ids->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('ids',$ids->toArray());
		}

		// position
		if(!isset($userValue["position"]) && $userValue["position"] <> '') {
			$positionList = $staffs->getPositionsByOrgId($auth->org_id);
			$this->assign('positions',$positionList);	
		}

*/
		// print_r($searchIdNo);
		Zend_Loader::loadClass("Staffs");
		$ids = new Staffs();
		$ids->loadWhere(" org_id = " . $auth->org_id);
		$this->assign('ids',$ids->toArray());
		
		$positionList = $staffs->getPositionsByOrgId($auth->org_id);
		$this->assign('positions',$positionList);

		$staffList = $staffs->getStaffsByOrgId($auth->org_id,$searchIdNo,$searchStatus,$searchPosition,$searchName);
		$this->setNoLayout();
		$this->assign("staffs",$staffList);
		
		// image
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$request = $_SERVER['HTTP_HOST'];
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		$this->assign("request",$request.$uploadPath);

		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('stafflistsub.tpl');
		}
		else {
			$this->render('stafflist.tpl');
		}
		
	}
	

	public function addnewdispatchAction(){
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("OrganizationOrganisms");
		//Zend_Loader::loadClass("Organismsizes");
		
		$auth = BaseAuth::getInstance();	
		
		if($auth->org_id) {
		
			$organism = new OrganizationOrganisms();
			$organismValue = $organism->getOrganismByOrgId($auth->org_id);

			//$sizearray = new Organismsizes();
			//$sizearray->load();
					
			//echo "<pre>";print_r($organismValue);echo "</pre>";
			
			//$cart = CartUtility::getDispatchPoCart();
			//$items=$cart->items;
			$this->assign("customerId",$this->getParam("customerId"));
			$this->assign("poid",$this->getParam("poid"));
			$this->assign("organisms",$organismValue);
			//$this->assign("sizes",$sizearray->toArray());
			$this->setNoLayout();
			$this->render('addnewdispatchitem.tpl');
		}
		
	}
	
	public function OrganismAttributeAction(){
		Zend_Loader::loadClass("OrganismAttributes");
		
		$org_organism_id = $this->getParam("org_organism_id");
		
		$attributes = new OrganismAttributes();
		
		$attValues = $attributes->getOrganismAttribute($org_organism_id); 
		
		$this->setNolayout();
		$this->assign("attribute",$attValues);
		$this->render("orgattribute.tpl");
		
	}
	
	public function saveNewDispatchItemAction(){
		
		Zend_Loader::loadClass("CartUtility");
		Zend_Loader::loadClass("OrganizationOrganism");
		Zend_Loader::loadClass("Organism");
		Zend_Loader::loadClass("OrganismAttribute");
		Zend_Loader::loadClass("Size");
		
		$userValue = $this->getParam("user");
		
		$cart = CartUtility::getDispatchPoCart();
		$items = $cart->items;
		
		//ECHO "<pre>";print_r($items);echo "</pre>";
		//ECHO "<pre>";print_r($userValue);echo "</pre>";
		$org_organism_id = $userValue['organism'];
		$attribute_id = $userValue['sizeage'];
		$qty = $userValue['qty'];
		
		$organizationOrganism = new OrganizationOrganism();
		$organizationOrganism->loadWhere(" org_organism_id = ". $org_organism_id);
		
		$organism = new Organism();
		$organism->loadWhere(" organism_id = ". $organizationOrganism->organism_id);
		
		$attribute = new OrganismAttribute();
		$attribute->loadWhere(" organism_attribute_id  = ". $attribute_id);
		
		$size = new Size();
		$size->loadWhere(" size_code = '". $attribute->size_code . "'");
		$count = count($items) + 1;
		if($qty) {
			$items[$count]['size'] = $size->size;
			$items[$count]['moid'] = $organism->moid;
			$items[$count]['common_name'] = $organism->name;
			$items[$count]['order_quantity'] = $qty;
			$items[$count]['size_code'] = $size->size_code;
			$items[$count]['order_amount'] = $organizationOrganism->base_price_sale * $qty;
			$items[$count]['scientific_name'] = $organism->scientific_name;
			$items[$count]['balance'] = $qty;
		}	
		//echo "<pre>";print_r($items);echo "</pre>";
		$cart->items = $items;
		
		
		$this->setNoLayout();
		$array[0]['details']  = $items;
		$this->assign("orders",$array);
		
		$this->assign("customerId",$this->getParam("customerId"));
		$this->assign("poid",$this->getParam("poid"));
		
		$this->render('dispatchorderdetail.tpl');
	}

	public function tankInspectionAction() {
	
		Zend_Loader::loadClass("TankInspections");	
		Zend_Loader::loadClass("EcoezUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
				
		// tanks
		if(!isset($userValue["tank"])) {
			Zend_Loader::loadClass("Tanks");
			$tankList = new Tanks();
			$tankList->loadWhere(" org_id = " . $auth->org_id);
			$this->assign('orgTanks',$tankList->toArray());
		}
		
		$ecoez = new EcoezUtility();
		$organization_id = $auth->org_id;
		$this->assign("orgSystems",$ecoez->getSystems($organization_id));
		
		// user values
		$searchSystem = $userValue["system"];
		$searchTank = $userValue["tank"];
		$searchResult = $userValue["result"];
		$searchFrom = $userValue["date_inspection_from"];
		$searchTo = $userValue["date_inspection_to"];
		
		$inspections = new TankInspections();
		$inspectionList = $inspections->getTankInspectionsByOrgId($auth->org_id,$searchTank,$searchResult,$searchFrom,$searchTo,$searchSystem);
		$this->setNoLayout();
		$this->assign("inspections",$inspectionList);
		
		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('tankinspectionlistsub.tpl');
		}
		else {
			$this->render('tankinspectionlist.tpl');
		}
		
	}
	
	public function editTankInspectionAction() {
		Zend_Loader::loadClass("EcoezUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("inspectionId");
		// tanks
		Zend_Loader::loadClass("Tanks");
		$tankList = new Tanks();
		$tankList->loadWhere(" org_id = " . $auth->org_id);
		$this->assign('orgTanks',$tankList->toArray());
		
		$ecoez = new EcoezUtility();

		$this->assign('orgSystems',$ecoez->getSystems($auth->org_id));
		$this->assign('tank_system',$ecoez->getSystemByTankInspectionID($userValue, $auth->org_id));
		
		Zend_Loader::loadClass("TankInspection");
		$inspection = new TankInspection();
		$inspection->loadWhere(" tank_inspection_id = " . $userValue);
		
		$this->assign('inspection',$inspection->toArray());
		
		$this->setNoLayout();
		$this->assign("id",$userValue);
		$this->render("edittankinspection.tpl");
		
	}
	
	public function saveTankInspectionAction() {	
		Zend_Loader::loadClass("EcoezUtility");

		$ecoez = new EcoezUtility();
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		$id = $auth->org_id;			

		$defaultValue = 0;
		
		if (isset($userValue['tank_inspection_id']) && $userValue['tank_inspection_id'] >0) {
			$defaultValue = $userValue['tank_inspection_id'];
		}	
			
		if ($userValue['tank'] <> "") {
			$ecoez->saveTankInspection($id, $userValue['tank'], $defaultValue, $userValue);
		} else {
			if ($userValue['system'] <> "") {
				$tanks = $ecoez->getTanksBySystem($userValue['system'], $auth->org_id);
				foreach($tanks as $tank) {					
					$ecoez->saveTankInspection($id, $tank['tank_id'], $defaultValue, $userValue);
				}
			}
		}
		
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/exporter/tankInspection/')");
		$this->render("empty.tpl");
		
	}
	
	public function tanksAction(){
		
		Zend_Loader::loadClass("Tanks");
		Zend_Loader::loadClass("EcoezUtility");
		
		$auth = BaseAuth::getInstance();
		$tanks = new Tanks();
				
		$userValue = $this->getParam("user");

		if ($userValue['system_name'] == "") {
			$tanks->loadWhere("org_id = " .  $auth->org_id." AND system_name ='none'", "name");	
			$srch_flag = 0;	
		} else if ($userValue['system_name'] == "all") {
			$tanks->loadWhere("org_id = " .  $auth->org_id, "name");	
			$srch_flag = 1;	
		} else {
			$tanks->loadWhere("org_id = ".$auth->org_id." AND system_name ='".$userValue['system_name']."'", "name");
			$srch_flag = 2;			
		}

		$ecoez = new EcoezUtility();
		
		$this->setNoLayout();
		$this->assign("systems",$ecoez->getSystems($auth->org_id));
		$this->assign("tanks",$tanks->toArray());
		$this->assign("srch_flag",$srch_flag);
		
		if ($srch_flag == 1 || $srch_flag == 2) {
			$this->render('tanklist.tpl');
		} else {
			$this->render('tank.tpl');
		}
		
	}
	
	public function editTankAction(){
		
		Zend_Loader::loadClass("Tank");
		
		$tankId = $this->getParam("tankId");
		$tank = new Tank();
		$tank->loadWhere("tank_id = " . $tankId);
		
		// $this->setLayout("accounts-inner.tpl");
		$this->setNoLayout();
		$this->assign("tank",$tank->toArray());
		$this->render("edittank.tpl");
		
	}
	
	public function saveTankAction() {
				
		Zend_Loader::loadClass("Tank");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if(isset($userValue['tank_id']) && $userValue['tank_id']) {
			$defaultValue = $userValue['tank_id'];
		}
		
		$tank = new Tank();
		$tank->loadWhere(" tank_id = " . $defaultValue);
		
		$tank->org_id = $auth->org_id;
		$tank->system_name = $userValue['system_name'];
		$tank->name = $userValue['name'];
		$tank->description = $userValue['description'];
		$tank->dimensions = $userValue['dimensions'];
		$tank->date_installed = $userValue['date_installed'];
		
		if(!$tank->tank_id) {
			$tank->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$tank->created_by = $auth->id;
		}
		$tank->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$tank->updated_by = $auth->id;
		$tank->save();
		
		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/tanks')");
		$this->render("empty.tpl");
		
	}
	
	public function editStaffAction() {
	
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("staffId");
		
		Zend_Loader::loadClass("Staff");
		$staff = new Staff();
		$staff->loadWhere(" staff_id = " . $userValue);
		$this->assign('staff',$staff->toArray());
		
		// address
		if($staff->address_id > 0) {
			Zend_Loader::loadClass("Address");
			$address = new Address();
			$addressValue = $address->getAddressById($staff->address_id);
			$this->assign('address',$addressValue[0]);
		}
		
		// contact
		if($staff->contact_id > 0) {
			Zend_Loader::loadClass("Contact");
			$contact = new Contact();
			$contactValue = $contact->getContactById($staff->contact_id);
			$this->assign('contact',$contactValue[0]);
		}
		
		// staff photo
		//print_r ($staff->photo_document_id);
		if($staff->photo_document_id > 0) {
			Zend_Loader::loadClass("Document");
			$doc = new Document();
			$doc->loadWhere(" document_id = " . $staff->photo_document_id);
			$this->assign('photo',$doc->toArray());
		}
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$request = $_SERVER['HTTP_HOST'];
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;

		$this->setNoLayout();
		$this->assign('id',$userValue);
		$this->assign("uploadDir",$request.$uploadPath);
		$this->render("editstaff.tpl");
		
	}
	
	public function saveStaffAction() {
	
		Zend_Loader::loadClass("Staff");
		Zend_Loader::loadClass("TimeUtility");
		Zend_Loader::loadClass("CartUtility");

		$cart = CartUtility::getAdminCart();
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		
		$defaultValue = 0;
		if(isset($userValue['staff_id']) && $userValue['staff_id']) {
			$defaultValue = $userValue['staff_id'];
		}
		
		$staff = new Staff();
		$staff->loadWhere(" staff_id = " . $defaultValue);
		
		$staff->org_id = $auth->org_id;
		$staff->first_name = $userValue['first_name'];
		$staff->last_name = $userValue['last_name'];
		$staff->middle_name = $userValue['middle_name'];
		$staff->identification_no = $userValue['identification_no'];
		$staff->position = $userValue['position'];
		$staff->date_hired = $userValue['date_hired'];
		$staff->date_resigned = $userValue['date_resigned'];
		$staff->email = $userValue['email'];
		$staff->gender = $userValue['gender'];
		$staff->date_birth = $userValue['date_birth'];
		$staff->remarks = $userValue['remarks'];
		
		// save document
		Zend_Loader::loadClass("Document");
		// print_r ($_FILES);
        $allowedFileTypes = array("gif", "jpeg", "jpg", "png");
		if (!empty($_FILES['uploadFile'])) {
			$pictureInput = $_FILES['uploadFile'];
			if (!empty($pictureInput['tmp_name'])) {
				Zend_Loader::loadClass("Zend_Session_Namespace");
				$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
				$uploadDIR = $client_session->CLIENT_DIR.$this->getConfig()->paths->upload;
				$uploadFileExt = strtolower(end(explode('.', $pictureInput['name'])));
				$fileName = strtolower(uniqid(rand())) .'.' . $uploadFileExt;
				copy($_FILES['uploadFile']['tmp_name'], $uploadDIR.'/'.$fileName);
				
				$uploadFile = new Document();
				$uploadFile->link = $fileName;
				$uploadFile->title = 'user image';
				$uploadFile->description = "user image";
				$uploadFile->date_created = date("Y-m-d H:i:s");
				$uploadFile->created_by = $auth->id;
				$uploadFile->save();
				$uploadFile->document_id = $uploadFile->id;
				$uploadFile->save();
				$this->assign("uploadFile", $uploadFile);
				$staff->photo_document_id = $uploadFile->document_id;
			}
		}

		if(!$staff->staff_id) {
			$staff->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$staff->created_by = $auth->id;
		}
		$staff->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$staff->updated_by = $auth->id;
		$staff->save();
		
		// $this->setLayout("ajax.tpl");
		// $this->assign("function","doajaxAction('/account/orgStaffs',0,')");
		// $this->assign("function","doajaxAction(action,0,'main_content')");
		// $this->render("empty.tpl");
		// $this->_redirect("/account/orgStaffs");
		$this->setNoLayout();
		//$this->assign('staffId',$staff->staff_id);
		//$this->render("editstaff.tpl");
		$cart->reload = 1;
		$this->orgStaffsAction();
	}
	
	public function staffTrainingsAction(){
		
		$auth = BaseAuth::getInstance();
		
		Zend_Loader::loadClass("Staffs");
		$staff = new Staffs();
		$staffValues = $staff->getStaffViewByOrgId($auth->org_id,1); 
		$this->assign("staffs",$staffValues);
		
		$this->setNoLayout();
		$this->render('stafftraininglist.tpl');
		
	}
	
	public function getStaffViewAction() {
		
		$auth = BaseAuth::getInstance();
		
		$view_type = $this->getParam("view_type");
		
		Zend_Loader::loadClass("Staffs");
		$staff = new Staffs();
		$staffValues = $staff->getStaffViewByOrgId($auth->org_id, $view_type);
		$this->assign("staffs",$staffValues);
		
		$this->setNoLayout();
		$this->render("staffsbyview.tpl");
		
	}

	public function getStaffTrainingAction() {
			
		$staffId = $this->getParam("staffId");
	
		Zend_Loader::loadClass("StaffTrainings");
		Zend_Loader::loadClass("StaffSkills");
		
		// training history
		$training = new StaffTrainings();
		$history = $training->getTrainingsByStaff($staffId);
		$this->assign("histories",$history);
		
		// schedules
		$schedules = $training->getTrainingScheduleByStaff($staffId);
		$this->assign("schedules",$schedules);
		
		// skills
		$skill = new StaffSkills();
		$skillValues = $skill->getSkillsByStaff($staffId);
		$this->assign("skills",$skillValues);
		
		$this->setNoLayout();
		$this->assign("staffId",$staffId);
		$this->render("staffsbyview.tpl");
		
	}

	public function createsspAction(){
		
		Zend_Loader::loadClass("Receipts");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		
		$searchFlg = $this->getParam("searchFlg");
		$search = $this->getParam("search");
		
		$organizations = new Organizations();
		
		$auth = BaseAuth::getInstance();
		
		$receipts = new Receipts();
		
		$receiptValue = $receipts->getReceipts($auth->org_id,$search,1);
		
		
		$userTypes = new UserTypes();
		
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_FMA);
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_EXPORTER);
				//$this->assign("countries",$countries->toArray());
				break;
		}
		
		
		//print_r($receiptValue);
		$this->assign("searchFlg",$searchFlg);
		$this->assign("suppliers",$suppliers);
		$this->assign("receipts",$receiptValue);
		
		
		$this->setNoLayout();
		$this->render();
	}

	function newsspAction() {
		
		Zend_Loader::loadClass("Receipt");
		
		$receipt_id = $this->getParam("receipt_id");
		
		$receipt = new Receipt();
		$receiptValue = $receipt->getReceipt($receipt_id);
		//print_r($receiptValue);
		$this->assign("receiptValue",$receiptValue);
		$this->setNoLayout();
		$this->render();
	}
	
	function savesspAction(){
		
		Zend_Loader::loadClass("SupplierPerformance");
		Zend_Loader::loadClass("SupplierPerformanceResult");
		Zend_Loader::loadClass("TimeUtility");
		$auth = BaseAuth::getInstance();
		
		$supplierPerformance = new SupplierPerformance();
		$supplierPerformanceResult = new SupplierPerformanceResult();
		
		$ssp_id = $this->getParam("ssp_id") ? $this->getParam("ssp_id") : 0;
		$supplier_org_id = $this->getParam("supplier_org_id");
		$receipt_id = $this->getParam("receipt_id");
		
		$overall = $this->getParam("overall");
		$doa = $this->getParam("doa");
		$unordered = $this->getParam("unordered");
		$size = $this->getParam("size");
		$water = $this->getParam("water");
		$packing = $this->getParam("packing");
		$comments = $this->getParam("comments");
		
		$supplierPerformance->loadWhere("ssp_id = ". $ssp_id);
		$supplierPerformance->evaluator_org_id = $auth->org_id;
		$supplierPerformance->supplier_org_id = $supplier_org_id;
		$supplierPerformance->reference_receipt_id = $receipt_id;
		$supplierPerformance->date_evaluated = date("Y-m-d");
		$supplierPerformance->overall_rate = $overall;
		$supplierPerformance->date_sent = date("Y-m-d");
		if(!isset($supplierPerformance->ssp_id)) {
			$supplierPerformance->date_created = date("Y-m-d");
			$supplierPerformance->created_by = $auth->id;
		} else {
			$supplierPerformance->date_updated = date("Y-m-d");
			$supplierPerformance->updated_by = $auth->id;
		}
		$supplierPerformance->comments = $comments;
		$supplierPerformance->save();
		
		$supplierPerformanceResult->loadWhere("ssp_id = ". $ssp_id);
		$supplierPerformanceResult->ssp_id = $supplierPerformance->ssp_id;
		$supplierPerformanceResult->doa = $doa;
		$supplierPerformanceResult->unordered_organism = $unordered;
		$supplierPerformanceResult->size = $size;
		$supplierPerformanceResult->water_quantity = $water;
		$supplierPerformanceResult->packing = $packing;
		if(!isset($supplierPerformanceResult->ssp_result_id)) {
			$supplierPerformanceResult->date_created = date("Y-m-d");
			$supplierPerformanceResult->created_by= $auth->id;
		} else {
			$supplierPerformanceResult->date_updated = date("Y-m-d");
			$supplierPerformanceResult->updated_by= $auth->id;
		}
		$supplierPerformanceResult->save();
		
		
		
	}
	
	public function viewsspAction(){
		
		Zend_Loader::loadClass("SupplierPerformances");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("PageUtility");
		Zend_Loader::loadClass("CartUtility");
		
		$searchFlg = $this->getParam("searchFlg");
		$search = $this->getParam("search");
		
		$page = $this->getParam("page");
		
		$auth = BaseAuth::getInstance();
		
		$supplierPerformance = new SupplierPerformances();
		$organizations = new Organizations();
		
		
		$userTypes = new UserTypes();
		
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		switch($org_type) {
			case CodesUtility::USER_TYPE_EXPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_FMA);
				break;
			case CodesUtility::USER_TYPE_IMPORTER:
				$suppliers = $organizations->getOrganizationSupplier(CodesUtility::USER_TYPE_EXPORTER);
				//$this->assign("countries",$countries->toArray());
				break;
		}
		
		
		$fields['date_evaluated'] = 'Date';
		$fields['po_no'] = 'PO No';
		$fields['name'] = 'Supplier';
		$fields['comments'] = 'Comments';
		
		$performance = $supplierPerformance->getSupplierPerformance($auth->org_id,$search);
		
		$cart = CartUtility::getToexcelCart();
		$cart->items = $performance;
		$cart->fields = $fields;
		
		$pagelist = array();
		if($page > 0) {		
			$list = PageUtility::pagination($performance,15,$page);
		
		} else {
			
			$list = PageUtility::pagination($performance,15,0);
		}
		$pagelist['pagelength'] = PageUtility::pagelength(10,round(count($performance)/15));
		$pagelist['action'] = "/account/viewssp/searchFlg/1";
		
		$this->assign("pagelist",$pagelist);
		
		
		
		$this->assign("searchFlg",$searchFlg);
		$this->assign("suppliers",$suppliers);
		$this->assign("performance",$list);
		$this->setNoLayout();
		$this->render();
		
	}
	
	public function saveCustomerAction() {
	
		Zend_Loader::loadClass("Organization");
		Zend_Loader::loadClass("CodesUtility");
		Zend_Loader::loadClass("Organizations");
		Zend_Loader::loadClass("CodesUtility");
		
		$newsupplier = $this->getParam("newsupplier");
		
		$organization = new Organization();
		
		$organization->name = $newsupplier;
		$organization->trading_name = $newsupplier;
		$organization->org_type = CodesUtility::USER_TYPE_IMPORTER_CUSTOMER;
		$organization->save();
		
		$customer = new Organizations();
		
		$customerValues = $customer->getOrganizationSupplier(CodesUtility::USER_TYPE_IMPORTER_CUSTOMER,array(0=>'name as supplier',1=>'org_id'));
		
		$this->assign("customers",$customerValues);
		$this->assign("selectedsupplier",$organization->org_id);
		$this->setNoLayout();
		$this->render("dispatchcustomer.tpl");
		
	}
	
	public function orsfishermanlistAction(){
	
		Zend_Loader::loadClass("Fishers");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getFishermanCart();
		$items = $cart->items;
		
		$supplier_org_id = $this->getParam("supplier_org_id");
		
		$podetailid = $this->getParam("podetailid");
		$auth = BaseAuth::getInstance();
		
		$podetailid = $this->getParam("podetailid");
		
		$fishers = new Fishers();
		
		$fisherValue = $fishers->getFirstherByOrg($supplier_org_id);
		//print_r($fisherValue);
		$this->assign("selectedvalue",$items[$podetailid]);
		$this->assign("podetailid",$podetailid);
		$this->assign("fisherValue",$fisherValue);
		$this->setNoLayout();
		$this->render();
		
	}
	
	public function saveorsfishermanAction(){
		
		Zend_Loader::loadClass("AccountUtility");
		
		$fishermanqty = $this->getParam("fishermanqty");
		$fishermandoaqty = $this->getParam("fishermandoaqty");
		$fishermanrejectqty = $this->getParam("fishermanrejectqty");
		$podetailid = $this->getParam("podetailid");
		
		AccountUtility::savefishermanCart($podetailid,$fishermanqty,$fishermandoaqty,$fishermanrejectqty);
		
		
		
	}
	
	public function fishermanrejectReasonAction(){
	
		Zend_Loader::loadClass("RejectReasons");	
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getFishermanCart();
		$items = $cart->items;
		
		//print_r($items);
		
		$id = $this->getParam("fisherid");
		$qty = $this->getParam("qty");
		$podetailid = $this->getParam("podetailid");
		
		$reasonList = new RejectReasons();
		$reasonList->loadWhere("1=1","reason");
		
		$this->assign("items",$items[$podetailid][$id]['rejectreason']);
		$this->assign("podetailid",$podetailid);
		$this->assign("qty",$qty);
		$this->assign("id",$id);
		$this->assign("reasonList",$reasonList->toArray());
		$this->setLayout('popup');
		
		$this->render('fishermanrejectreason.tpl');
	}
	
	public function saveFishermanReasonAction(){
	
		Zend_Loader::loadClass("AccountUtility");
	
		$fisherid = $this->getParam("id");
		$podetailid = $this->getParam("podetailid");
	
		$reason = $this->getParam("reason");
		AccountUtility::savefishermanReasonCart($podetailid,$fisherid,$reason);
		
	}
	
	
	public function editStaffSkillAction(){
		
		Zend_Loader::loadClass("StaffSkills");
		Zend_Loader::loadClass("Skills");
		
		$staffId = $this->getParam("staffId");
		$staffSkillId = $this->getParam("staffSkillId");

		// skills
		/*if(!isset($userValue["skill"])) {
			Zend_Loader::loadClass("Skills");
			$skillList = new Skills();
			$skillList->loadWhere(" 1=1 ");
			$this->assign('skills',$skillList->toArray());
		}*/
		
		$skills = new Skills();
		$skills->loadWhere("1 = 1");
		
		$staffSkill = new StaffSkills();
		$staffSkillValue = $staffSkill->getSkillsByStaffSkill($staffSkillId);

		$this->setNoLayout();
		$this->assign("skills",$skills->toArray());
		$this->assign("staffId",$staffId);
		$this->assign("staffSkill", $staffSkillValue);
		$this->render("editStaffSkill.tpl");

	}
	
	public function saveStaffSkillAction() {
	
		Zend_Loader::loadClass("StaffSkill");
		Zend_Loader::loadClass("TimeUtility");

		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");

		$defaultValue = 0;
		if(isset($userValue['staff_skill_id']) && $userValue['staff_skill_id']){
			$defaultValue = $userValue['staff_skill_id'];
		}
		$staffSkill = new StaffSkill();
		$staffSkill->loadWhere(" staff_skills_id = " . $defaultValue);

		$staffSkill->staff_id = $userValue['staff_id'];
		$staffSkill->skill_id = $userValue['skill'];
		$staffSkill->level = $userValue['level'];
		$staffSkill->date_acquired = $userValue['date_acquired'];
		$staffSkill->remarks = $userValue['remarks'];

		if(!$staffSkill->staff_skill_id) {
			$staffSkill->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$staffSkill->created_by = $auth->id;
		}
		$staffSkill->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$staffSkill->updated_by = $auth->id;
		$staffSkill->save();

		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/staffTrainings')");
		$this->render("empty.tpl");

	}
	
	public function getStaffTrainingListAction() {

		Zend_Loader::loadClass("StaffTrainings");
		Zend_Loader::loadClass("Staff");

		$auth = BaseAuth::getInstance();
		$staffId = $this->getParam("staffId");
		
		$staffTraining = new StaffTrainings();
		$staffTrainingList = $staffTraining->getStaffTrainingListByOrg($auth->org_id, $staffId);

		// get the name of the staff
		$staff = new Staff();
		$staffName = $staff->getStaffCompleteName($staffId);

		$this->setNoLayout();
		$this->assign('staffId',$staffId);
		$this->assign('staff_name',$staffName);
		$this->assign('trainings',$staffTrainingList);
		$this->render("staffTrainingSchedule.tpl");

	}

	public function editStaffTrainingAction(){

		Zend_Loader::loadClass("StaffTrainings");
		Zend_Loader::loadClass("Skills");

		$auth = BaseAuth::getInstance();
		$staffTrainingId = $this->getParam("staffTrainingId");
		$staffId = $this->getParam("staffId");
		
		$staffTraining = new StaffTrainings();
		// $staffTraining->loadWhere("staff_training_id = " . $staffTrainingId);
		$staffTrainingList = $staffTraining->getStaffTrainingByTraining($auth->org_id,$staffTrainingId);

		$skills = new Skills();
		$skills->loadWhere("1 = 1");

		$this->setNoLayout();
		$this->assign("staffTraining",$staffTrainingList);
		$this->assign("skills",$skills->toArray());
		$this->assign("staffId",$staffId);
		$this->render("editStaffTraining.tpl");

	}

	public function saveStaffTrainingAction() {

		Zend_Loader::loadClass("StaffTraining");
		Zend_Loader::loadClass("TimeUtility");

		$userValue = $this->getParam("user");

		$defaultValue = 0;
		if(isset($userValue['staff_training_id']) && $userValue['staff_training_id']) {
			$defaultValue = $userValue['staff_training_id'];
		}
		$staffTraining = new StaffTraining();
		$staffTraining->loadWhere(" staff_training_id = " . $defaultValue);
		
		$staffTraining->default_trainor = $userValue['default_trainor'];
		$staffTraining->date_default_trained = $userValue['date_default_trained'];
		$staffTraining->actual_trainor = $userValue['actual_trainor'];
		$staffTraining->date_actual_trained = $userValue['date_actual_trained'];
		$staffTraining->remarks = $userValue['remarks'];
		if($userValue['cancel'] == 'on') {
			$staffTraining->cancel = 1;
		} else {
			$staffTraining->cancel = 0;
		}
		if(!$staffTraining->staff_training_id) {
			$staffTraining->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
			$staffTraining->created_by = $auth->id;
		}
		$staffTraining->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$staffTraining->updated_by = $auth->id;
		$staffTraining->save();

		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/staffTrainings')");
		$this->render("empty.tpl");

	}

	public function downloadInventoryAction(){
	
		Zend_Loader::loadClass("ReportsUtility");
		Zend_Loader::loadClass("ExcelWriter");
		Zend_Loader::loadClass("Inventories");
		
		
		
		$auth = BaseAuth::getInstance();
		
		$inventories = new Inventories();
		$data = $inventories->exportFile($auth->org_id);
		
		//echo "<pre>";print_r($data);echo "</pre>";
		
		$header= array("MOID","Common Name","Size Code","Size","TankID","Tank","Quantity","Cost");
		
		$excelWriter = new ExcelWriter();
		$filename = mt_rand();
		$excelWriter->ExcelWriter($filename.".xls");
		$head = $excelWriter->getHeader();
		$excelWriter->writeLine($head);
		$excelWriter->writeLine($header);
		foreach($data as $key => $value){
			$excelWriter->writeLine($value);
		}
		
		$excelWriter->close();
	
		
		//ReportsUtility::exportReport($data,$header,"xls");
		//$this->setLayout("popupclose");
		$this->setNoLayout();
		$this->assign("host",$_SERVER['HTTP_HOST']);
		$this->assign("filename",$filename.".xls");
		$this->render("../admin/downloadfile.tpl");
	}
	
	public function stockuploadingAction(){
	
		$this->setNoLayout();
		$this->render("");
	
	}
	public function saveuploadFileAction() {
		Zend_Loader::loadClass("Inventory");
		Zend_Loader::loadClass("TimeUtility");
		Zend_Loader::loadClass("CartUtility");
	
		$auth = BaseAuth::getInstance();
	
		$cart = CartUtility::getUploadCart();
		$items = $cart->items;
		$inventory = new Inventory();
		if(count($items)) {
			foreach($items as $key => $value) {
				$inventory->clear();
				if($value['valid']) {
					$inventory->loadWhere("org_id  =". $auth->org_id . " and tank_id = ". $value['tankid'] . " and org_organism_id = ". $value['org_organism_id']. " and organism_attribute_id = ". $value['organism_attribute_id']);
					$inventory->org_id = $auth->org_id;
					$inventory->tank_id =  $value['tankid'];
					$inventory->org_organism_id = $value['org_organism_id'];
					$inventory->organism_attribute_id = $value['organism_attribute_id'];
					$inventory->quantity_on_hand = $inventory->quantity_on_hand + $value['quantity'];
					$inventory->unit = $value['unit'];
					$inventory->currency_mark = $value['currency_mark'];
					$inventory->stock_amount = $inventory->stock_amount + ($value['quantity'] * $value['cost']);
					if($inventory->inventory_id) {
						$inventory->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y'));
						$inventory->updated_by = $auth->id;
					} else {
						$inventory->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y'));
						$inventory->created_by = $auth->id;
					}
					
					$inventory->save();
					
				}
			}
		
			$cart->items = array();
			$this->setNoLayout();
			$this->render("successfullyupload.tpl");
		} 
	}
	public function readuploadFileAction(){
		Zend_Loader::loadClass("ExcelReader");
		Zend_Loader::loadClass("Organism");
		Zend_Loader::loadClass("Size");
		Zend_Loader::loadClass("Tank");
		Zend_Loader::loadClass("OrganismAttribute");
		Zend_Loader::loadClass("OrganizationOrganism");
		Zend_Loader::loadClass("CartUtility");
		
		$cart = CartUtility::getUploadCart();
		$items = $cart->items;
		
		
		$organism = new Organism();
		$size = new Size();
		$tank = new Tank();
		$organismAttribute = new OrganismAttribute();
		$organizationOrganism = new OrganizationOrganism();
		
		$auth = BaseAuth::getInstance();
		
	    $allowedFileTypes = array("xls");
		$i = 1;
		
		//print_r($_FILES);
		$pictureInput = $_FILES['uploadedFile'];
		
		$excelread = new ExcelReader();
		
		$excelread->read($pictureInput['tmp_name']);
		
		$row = $excelread->getTotalRows();
		//echo $row;
		$data = array();
		for($i=2;$i <= $row;$i++){ 
			
			$moid = $excelread->getValue($i,1);
			$sizecode = $excelread->getValue($i,3);
			$tankid = $excelread->getValue($i,5);
			
			//echo $tankid;die();
			//echo $moid;
			$moid_length = 6 - strlen($moid);

			if ($moid_length > 0) {
				$moid = str_pad($moid, 6, "0", STR_PAD_LEFT);
			}
			$organism->clear();
			$organism->loadWhere("moid = '". $moid ."'" );
			if($organism->organism_id) {
				$valid = 1;
			} else {
				$valid = 0;
			}

			$size->clear();
		
			$size->loadWhere(" size_code = '". $sizecode . "'" );
			
			if($size->size_code && $valid ) {
				$valid = 1;
			} else {
				$valid = 0;
			}

			
			$tank->clear();
			$tank->loadWhere(" tank_id = '". $tankid. "' and org_id = ".  $auth->org_id  );
			if($tank->tank_id && $valid ) {
				$valid = 1;
			} else {
				$valid = 0;
			}

			if($valid) {
			
				$organizationOrganism->clear();
				$organizationOrganism->loadWhere(" org_id = ". $auth->org_id . " and organism_id = ". $organism->organism_id);
			
				$organismAttribute->clear();
				$organismAttribute->loadWhere(" organism_id = ". $organism->organism_id . " and size_code = '". $sizecode . "'");
				
				$data[$i]['organism_attribute_id'] = $organismAttribute->organism_attribute_id;
				$data[$i]['org_organism_id'] = $organizationOrganism->org_organism_id;
				$data[$i]['unit'] = $organism->sale_unit;
				$data[$i]['currency_mark'] = $organizationOrganism->currency_mark;
			}
			
			$data[$i]['moid'] = $excelread->getValue($i,1);
			$data[$i]['common_name'] = $excelread->getValue($i,2);
			$data[$i]['size_code']  = $excelread->getValue($i,3);
			$data[$i]['size'] = $excelread->getValue($i,4);
			$data[$i]['tankid'] = $excelread->getValue($i,5);
			$data[$i]['tank'] = $excelread->getValue($i,6);
			$data[$i]['quantity'] = $excelread->getValue($i,7);
			$data[$i]['cost'] = $excelread->getValue($i,8);
			$data[$i]['valid'] = $valid;
			
			
			
		}
		
	//	echo "<pre>";print_r($data); echo "</pre>";
		$cart->items = $data;
		$this->setNoLayout();
		$this->assign("data",$data);
		$this->render("stockupload.tpl");
		
	}

	public function documentLibraryAction(){
		
		Zend_Loader::loadClass("DocumentLibraries");
		Zend_Loader::loadClass("UserTypes");
		Zend_Loader::loadClass("Zend_Session_Namespace");
		
		$auth = BaseAuth::getInstance();
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];
		//ECHO phpinfo();
		$request = $_SERVER['HTTP_HOST'];
		//echo $request;
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		$uploadPath = $client_session->CLIENT_WWW.$this->getConfig()->paths->upload;
		//echo $uploadPath;
		$documents = new DocumentLibraries();
		$documentList = $documents->getDocumentsByOrgType($org_type);
		$this->assign("documents",$documentList);
		$this->assign("request",$request);
		$this->setNoLayout();
		$this->render('documentLibrary.tpl');
		
	}

	public function exporterShipmentSummaryReportAction() {
	
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");

		// country
		if(!isset($userValue["country"])) {
			Zend_Loader::loadClass("Organizations");
			$org = new Organizations();
			$orgCountries = $org->getOrgTypeCountries('Exporter');
			$this->assign("countries",$orgCountries);
		}
		
		// province
		if(!isset($userValue["province"])) {
			Zend_Loader::loadClass("Organizations");
			$org = new Organizations();
			$orgProvinces = $org->getOrgTypeProvinces('Exporter');
			$this->assign("provinces",$orgProvinces);
		}

		// exporter
		if(!isset($userValue["exporter"])) {
			Zend_Loader::loadClass("Organizations");
			$exporters = new Organizations();
			$exporters->loadWhere(" org_type = 'Exporter'");
			$this->assign("exporters",$exporters->toArray());
		}
		
		// user values
		$searchCountry = $userValue["country"];
		$searchProvince = $userValue["province"];
		$searchExporter = $userValue["exporter"];
		$searchDateFrom = $userValue["dateFrom"];
		$searchDateTo = $userValue["dateTo"];

		// get the shipments
		Zend_Loader::loadClass("Shipments");
		$shipment = new Shipments();
		$shipments = $shipment->getMonthlyListOfShipmentSummary('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);

		// get the DOAs
		Zend_Loader::loadClass("Receipts");
		$receipt = new Receipts();
		$receipts = $receipt->getMonthlyListOfDOASummary('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);

		// get the rejects
		Zend_Loader::loadClass("ReceiptRejects");
		$reject = new ReceiptRejects();
		$rejects = $reject->getMonthlyListOfRejectSummary('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);
	
		// get the calendar
		Zend_Loader::loadClass("CalendarYearMonthNames");
		$calendar = new CalendarYearMonthNames();
		$yearmonth = $calendar->getYearMonthNames($searchDateFrom,$searchDateTo);
		
		if((isset($userValue["shipment_summary"]) &&  $userValue["shipment_summary"] == 'on') ||
			(isset($userValue["organism_shipment"]) &&  $userValue["organism_shipment"] == 'on')) {
			$summary = $shipment->getMonthlyListOfShipmentDetail('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);
			$org = $shipment->getMonthlyCountOfSupplierDetail('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);
			$total = $shipment->getMonthlySumOfShipmentDetail('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);
			$this->assign("details",$summary);
			$this->assign("orgs",$org);
			$this->assign("totals",$total);
		}
		if(isset($userValue["shipment_summary"]) &&  $userValue["shipment_summary"] == 'on') {
			$this->assign("show_shipment_summary",'1');
		}
		else {
			$this->assign("show_shipment_summary",'0');
		}
		if(isset($userValue["organism_shipment"]) &&  $userValue["organism_shipment"] == 'on') {
			$this->assign("show_organism_shipment",'1');
		}
		else {
			$this->assign("show_organism_shipment",'0');
		}

		// default date current year
		$dt = getdate();

		$this->setNoLayout();
		$this->assign("shipments",$shipments);
		$this->assign("doas",$receipts);
		$this->assign("rejects",$rejects);
		$this->assign("yearmonth",$yearmonth);
		$this->assign("dtFrom",$dt["year"].'-01'.'-01');
		$this->assign("dtTo",$dt["year"].'-12'.'-31');

		// echo "<pre>";print_r($userValue["shipment_summary"]);echo "</pre>";die();

		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('exporterShipmentSummaryReportSub.tpl');
		}
		else {
			$this->render('exporterShipmentSummaryReport.tpl');
		}
	}

	public function emailMessageAction() {

		Zend_Loader::loadClass("EmailMessages");

		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");

		$message = new EmailMessages();

		// user values
		$searchType = $userValue["type"];
		$searchMail = $userValue["mail"];
		$searchReadStatus = $userValue["read_status"];
		$searchDateFrom = $userValue["date_sent_from"];
		$searchDateTo = $userValue["date_sent_to"];
		
		$view_type = $this->getParam("view_type");
		if(isset($view_type)) { $searchType = $view_type; }

		if($searchType == '1') {
			$recipients = $message->getOrgRecipients($auth->org_id);
			$this->assign("owners",$recipients);
			// echo "<pre>";print_r('source');echo "</pre>";
			$messages = $message->getOrgMessagesSource($auth->org_id,$searchMail,$searchReadStatus,$searchDateFrom,$searchDateTo);
		} else {
			$senders = $message->getOrgSenders($auth->org_id);
			$this->assign("owners",$senders);
			// echo "<pre>";print_r('recipient');echo "</pre>";
			$messages = $message->getOrgMessagesRecipient($auth->org_id,$searchMail,$searchReadStatus,$searchDateFrom,$searchDateTo);
		}

		$this->setNoLayout();
		$this->assign("userType",$searchType);
		$this->assign("messages",$messages);

		$reload = $this->getParam("reload");
		if ($reload == '1') {
			$this->render('emailMessagesSub.tpl');
		}
		else {
			$this->render('emailMessages.tpl');
		}
	}

	public function getMessageViewAction() {
		
		Zend_Loader::loadClass("EmailMessages");

		$auth = BaseAuth::getInstance();
		$searchType = $this->getParam("view_type");
		
		$message = new EmailMessages();
		if($searchType == '1') {
			// recipients
			$recipients = $message->getOrgRecipients($auth->org_id);
			$this->assign("owners",$recipients);
		} else {
			// senders
			$senders = $message->getOrgSenders($auth->org_id);
			$this->assign("owners",$senders);
		}

		$this->setNoLayout();
		$this->assign("userType",$searchType);
		$this->render("emailMessageView.tpl");		
	}

	public function newMessageAction(){

		Zend_Loader::loadClass("EmailMessages");
		Zend_Loader::loadClass("UserTypes");
		
		$auth = BaseAuth::getInstance();
		$userTypes = new UserTypes();
		$userTypesArray = $userTypes->getUserTypesArray("id", "code");
		$org_type = $userTypesArray[$auth->user_type_id];

		//echo "<pre>";print_r($org_type);echo "</pre>";
		
		$messages = new EmailMessages();
		$recipients = $messages->getMailRecipients($org_type);
		$this->assign("owners",$recipients);

		$this->setNoLayout();
		$this->render('newMessage.tpl');

	}

	public function saveMessageAction() {

		Zend_Loader::loadClass("EmailMessage");
		Zend_Loader::loadClass("TimeUtility");
		
		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");

		$message = new EmailMessage();
		$message->loadWhere(" 1=0 ");

		$message->source_org_id = $auth->org_id;
		$message->recipient_org_id = $userValue['recipient'];
		$message->subject = $userValue['subject'];
		$message->message = $userValue['body'];
		
		$message->date_sent = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$message->date_created = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$message->created_by = $auth->id;
		$message->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$message->updated_by = $auth->id;
		
		$message->save();

		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/emailMessage')");
		$this->render("empty.tpl");

	}

	public function readMessageAction(){

		Zend_Loader::loadClass("EmailMessages");

		$messageId = $this->getParam("messageId");
		$viewType = $this->getParam("viewType");
		// echo "<pre>";print_r($messageId);echo "</pre>";die();
		$messages = new EmailMessages();
		$message = $messages->getMessageData($messageId);

		$this->setNoLayout();
		$this->assign("message",$message);
		$this->assign("viewType",$viewType);
		$this->render("readMessage.tpl");

	}

	public function setReadMessageAction() {

		Zend_Loader::loadClass("EmailMessage");
		Zend_Loader::loadClass("TimeUtility");

		$messageId = $this->getParam("messageId");
		$message = new EmailMessage();
		$message->loadWhere(" message_id = " . $messageId);

		$message->read = '1' ;
		$message->date_read = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$message->save();
		
		$this->setLayout("ajax.tpl");
		$this->assign("reload",'1');
		$this->assign("function","changeTabView('/account/emailMessage')");
		$this->render("empty.tpl");

	}

	public function setCancelMessageAction() {

		Zend_Loader::loadClass("EmailMessage");
		Zend_Loader::loadClass("TimeUtility");

		$messageId = $this->getParam("messageId");
		$message = new EmailMessage();
		$message->loadWhere(" message_id = " . $messageId);

		$message->cancel = '1';
		$message->date_cancel = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$message->save();
		
		$this->setLayout("ajax.tpl");
		// $this->assign("reload",'1');
		$this->assign("function","changeTabView('/account/emailMessage')");
		$this->render("empty.tpl");

	}

	public function mapAction(){
		Zend_Loader::loadClass("MenuUtility");
		
		$this->setNoLayout();
		$auth = BaseAuth::getInstance();
  		$this->assign("username",$auth->username);
		
		$menuUtility = new MenuUtility();
		$this->assign("menuUtility" ,$menuUtility);
		
	
		$this->render("map.tpl");
	}

	public function editOrgOrganismAction(){

		Zend_Loader::loadClass("OrganizationOrganism");
		Zend_Loader::loadClass("Organism");
		Zend_Loader::loadClass("Currencies");

		$orgOrgId = $this->getParam("orgOrgId");

		$orgOrg = new OrganizationOrganism();
		$orgOrg->loadWhere("org_organism_id = " . $orgOrgId);

		// currencies
		$currencies = new Currencies();
		$currenciesValues = $currencies->getCurrencies();
		
		$orgOrganisms[] = $orgOrg->toArray();

		// organism
		$organism = new Organism();
		$organism->loadWhere("organism_id = " . $orgOrganisms[0]['organism_id']);

		$this->setNoLayout();
		$this->assign("orgOrganism",$orgOrg->toArray());
		$this->assign("currencies",$currenciesValues);
		$this->assign("organism",$organism->toArray());
		$this->render("editOrgOrganism.tpl");

	}

	public function saveOrgOrganismAction(){

		Zend_Loader::loadClass("OrganizationOrganism");
		Zend_Loader::loadClass("TimeUtility");

		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");

		$defaultValue = 0;
		if(isset($userValue['org_organism_id']) && $userValue['org_organism_id']) {
			$defaultValue = $userValue['org_organism_id'];
		}

		$orgOrg = new OrganizationOrganism();
		$orgOrg->loadWhere(" org_organism_id = " . $defaultValue);

		$orgOrg->ordering_status = $userValue['ordering_status'];
		$orgOrg->estimated_buy = $userValue['estimated_buy'];
		$orgOrg->non_taxable = $userValue['non_taxable'];
		$orgOrg->base_price_sale = $userValue['base_price_sale'];
		$orgOrg->reorder_level = $userValue['reorder_level'];
		$orgOrg->min_order = $userValue['min_order'];
		$orgOrg->lead_days = $userValue['lead_days'];
		$orgOrg->currency_mark = $userValue['currency_mark'];
		$orgOrg->notes = $userValue['notes'];

		$orgOrg->date_updated = TimeUtility::convertToSQLDateFormat(date('m/d/y H:i:s'));
		$orgOrg->updated_by = $auth->id;
		$orgOrg->save();

		$this->setLayout("ajax.tpl");
		$this->assign("function","changeTabView('/account/orgOrganismLookup')");
		$this->render("empty.tpl");

	}

	public function exporterTrackingShipmentReportAction() {

		$auth = BaseAuth::getInstance();
		$userValue = $this->getParam("user");
		$reload = $this->getParam("reload");

		// country
		if(!isset($userValue["country"])) {
			Zend_Loader::loadClass("Organizations");
			$org = new Organizations();
			$orgCountries = $org->getOrgTypeCountries('Exporter');
			$this->assign("countries",$orgCountries);
		}
		
		// province
		if(!isset($userValue["province"])) {
			Zend_Loader::loadClass("Organizations");
			$org = new Organizations();
			$orgProvinces = $org->getOrgTypeProvinces('Exporter');
			$this->assign("provinces",$orgProvinces);
		}

		// exporter
		if(!isset($userValue["exporter"])) {
			Zend_Loader::loadClass("Organizations");
			$exporters = new Organizations();
			$exporters->loadWhere(" org_type = 'Exporter'");
			$this->assign("exporters",$exporters->toArray());
		}
		
		$searchPage = '0';
		if ($reload == '1') {
			// user values
			$searchCountry = $userValue["country"];
			$searchProvince = $userValue["province"];
			$searchExporter = $userValue["exporter"];
			$searchDateFrom = $userValue["dateFrom"];
			$searchDateTo = $userValue["dateTo"];
			$searchPage = $this->getParam("page");
			
			Zend_Loader::loadClass("Shipments");
			$shipment = new Shipments();

			if(strlen($searchPage) <= 0) { $searchPage = '0'; }

			// get the exporter in focus
			$exp = $shipment->getShipmentExporters('Exporter',$searchExporter,$searchPage, 1, $searchCountry,$searchProvince,$searchDateFrom,$searchDateTo);
			
			// print_r($exp->toArray());die();
			if(isset($searchExporter) && isset($exp[0]) && $searchExporter <= 0) {
				$searchExporter = $exp[0]['org_id'];
			}

			// get the shipments
			$shipments = $shipment->getShipmentTrackingSummary('Exporter',$searchCountry,$searchProvince,$searchExporter,$searchDateFrom,$searchDateTo);
			$this->assign("shipments",$shipments);

			// get the shipment dates of the exporter
			$shipDates = $shipment->getOrgShipmentDates('Exporter',$searchExporter);
			$this->assign("shipDates",$shipDates);

			// get the count of suppliers for this filter
			$cexp = $shipment->getShipmentExporters('Exporter',0,0,0, $searchCountry,$searchProvince,$searchDateFrom,$searchDateTo);
			$this->assign("curr_exporter",$exp);
			$this->assign("exporters",$cexp);

			// get the importers for this exporter
			$imp = $shipment->getOrgShipmentOrgs('Exporter',$searchExporter,$searchCountry,$searchProvince,$searchDateFrom,$searchDateTo);
			$this->assign("importers",$imp);
			
			// get the count of importers
			$impcount = $shipment->getCountOrgShipmentOrgs('Exporter',$searchExporter,$searchCountry,$searchProvince,$searchDateFrom,$searchDateTo);
			$this->assign("importer_count",$impcount);

		}		


		
		// default date current year
		$dt = getdate();

		$this->setNoLayout();
		$this->assign("dtFrom",date("Y-m-d"));
		$this->assign("dtTo",date("Y-m-d"));
		$this->assign("page",$searchPage);
		$this->assign("reload",$reload);

		if ($reload == '1') {
			$this->render('exporterShipmentTrackingReportSub.tpl');
		}
		else {
			$this->render('exporterShipmentTrackingReport.tpl');
		}

	}
	
	public function uploadFileFromLocalAction(){
		//read the directory
		//ECHO phpinfo();
		
		Zend_Loader::loadClass("Receipt");
		Zend_Loader::loadClass("ReceiptReject");
		Zend_Loader::loadClass("AccountUtility");
		
		$userid = $this->getParam("userid");
		
		$curdir = getcwd();
		if(stripos($curdir,"docroot") > 0) {
			$directory = "uploadfile";
		} else {
			$directory = "docroot/uploadfile";
		}
		$docroot = $_SERVER["DOCUMENT_ROOT"];
		$orderf = $this->getParam("orderf");
		if(strlen($orderf)) {
			$fh = fopen($directory."/".$orderf,"r");
			if($fh) {
				$table ='';
				$head = array();
				$detail = array();
				while (!feof($fh)) {
					$line = '';
					$contents = trim(fgets($fh));
					if(strlen($contents)) {
						
						if(trim($contents) == 'Orders') {
							$table = 'Orders';
							continue;
						}
						if(trim($contents) == 'Order Detail') {
							$table = 'Order Detail';
							continue;
						}
						
						if($table == 'Orders') {
							$line = explode(",",$contents);
							$head[$line[0]] = $line;
							
						}
						if($table == 'Order Detail') {
							$line = explode(",",$contents);
							$detail[$line[1]][] = $line;
						}
						
					}
				}
				fclose($fh);
				unlink($directory."/".$orderf);
				AccountUtility::saveexportOrder($head,$detail,$userid);
			}
		}
		
		$orsf = $this->getParam("orsf");
		if(strlen($orsf)) { 
			$fh = fopen($directory."/".$orsf,"r");
			if($fh) {
				$table ='';
				$head = array();
				$detail = array();
				while (!feof($fh)) {
					$line = '';
					$contents = trim(fgets($fh));
					if(strlen($contents)) {
						if( trim($contents) == "Receipts" ) {
							$table = 'Receipts';
							continue;
						}
						if( trim($contents) == 'Receipts Reject') {
							$table = 'Receipts Reject';
							continue;
						}
						if($table == 'Receipts') {
							$line = explode(",",$contents);
							$head[$line[1]] = $line;
							
						}
						if($table == 'Receipts Reject') {
							$line = explode(",",$contents);
							$detail[$line[1]][] = $line;
						}
					}
				}
				
				fclose($fh);
				unlink($directory."/".$orsf);
				AccountUtility::saveexportReceipt($head,$detail,$userid);
			}
		}
		
		$dispatchingf = $this->getParam("dispatchingf");
		if(strlen($dispatchingf)) {
			$fh = fopen($directory."/".$dispatchingf,"r");
			if($fh) {
				$table ='';
				$head = array();
				$detail = array();
				$ref = array();
				while (!feof($fh)) {
					$line = '';
					$contents = trim(fgets($fh));
					if(strlen($contents)) {
						if( trim($contents) == "Shipment" ) {
							$table = 'Shipment';
							continue;
						}
						if( trim($contents) == 'Shipment Details') {
							$table = 'Shipment Details';
							continue;
						}
						if( trim($contents) == 'Ref') {
							$table = 'Ref';
							continue;
						}
						
						if($table == "Shipment") {
							$line = explode(",",$contents);
							$head[$line[1]] = $line;
							
						}
						if($table == 'Shipment Details') {
							$line = explode(",",$contents);
							$detail[$line[1]][] = $line;
						}
						if($table == 'Ref'){
							$line = explode(",",$contents);
							$ref[$line[0]][] = $line;
						}
					}
				}
				
				fclose($fh);
				unlink($directory."/".$dispatchingf);
				AccountUtility::saveexportShipment($head,$detail,$userid,$ref);	
			}
		}
		
		$performancef = $this->getParam("performancef");
		if($performancef) {
			$fh = fopen($directory."/".$performancef,"r");
			if($fh) {
				$table ='';
				$head = array();
				$detail = array();
				while (!feof($fh)) {
					$line = '';
					$contents = trim(fgets($fh));
					if(strlen($contents)) {
						if( trim($contents) == "Supplier Performance" ) {
							$table = 'Supplier Performance';
							continue;
						}
						if( trim($contents) == 'Supplier Performance Result') {
							$table = 'Supplier Performance Result';
							continue;
						}
						if($table == "Supplier Performance") {
							$line = explode(",",$contents);
							$head[$line[0]] = $line;
							
						}
						if($table == 'Supplier Performance Result') {
							$line = explode(",",$contents);
							$detail[$line[1]][] = $line;
						}
					}
				}
				//print_r($detail);die();
				fclose($fh);
				unlink($directory."/".$performancef);
				AccountUtility::saveexportPerformance($head,$detail,$userid);	
			}
		}
		
		$this->setLayout("popupclose");		
		$this->assign("closeonly",1);
		$this->render("../globals/blank.tpl");
	}
	
	public function dumpmasterfileAction(){
	
		//get the local server to render again for ftp and save the sql file
		//and run the mysqldump
		Zend_Loader::loadClass("DumpUtility");
		Zend_Loader::loadClass("AccountUtility");
		
		$localdb = $this->getParam("localdb");
		$localserver = $this->getParam("localserver");
		$u = $this->getConfig()->database->username;
		$p = $this->getConfig()->database->password;
		//orgid
		$userid = $this->getParam("userid");
		//
		$curdir = getcwd();
		if(stripos($curdir,"docroot") > 0) {
			$directory = "uploadfile/";
		} else {
			$directory = "docroot/uploadfile/";
		}
		
		$localdbArr = explode("_",$localdb);
		
		$db = $this->getConfig()->database->dbname;
		$dbar = explode("_",$db);
	
		$dbprefix = $dbar[0];
		
		$dbarray ="account_organizations,address_coordinates,addresses,contacts,fishers,fishing_area,organization_addresses,organization_contacts,organization_documents,organizations";
		
		$inventory = DumpUtility::_mysqldump($dbprefix."_inventory",'',$userid,$localdbArr[0]."_inventory");
		$ref = DumpUtility::_mysqldump($dbprefix."_ref",'',$userid,$localdbArr[0]."_ref");
		$trade = DumpUtility::_mysqldump($dbprefix."_trade",'',$userid,$localdbArr[0]."_trade");
		$entity = DumpUtility::_mysqldump($dbprefix."_entity",$dbarray,$userid,$localdbArr[0]."_entity");
		
		$filename = $directory.'inventory.sql';
		$handle = fopen($filename, 'w+');
		foreach($inventory as $key => $value){
			fwrite($handle,$value);
		}
		fclose($handle);
		
		$filename = $directory.'ref.sql';
		$handle = fopen($filename, 'w+');
		foreach($ref as $key => $value){
			fwrite($handle,$value);
		}
		fclose($handle);
		
		$filename = $directory.'trade.sql';
		$handle = fopen($filename, 'w+');
		foreach($trade as $key => $value){
			fwrite($handle,$value);
		}
		fclose($handle);
		
		$filename = $directory.'entity.sql';
		$handle = fopen($filename, 'w+');
		foreach($entity as $key => $value){
			fwrite($handle,$value);
		}
		fclose($handle);
		
		//order
		Zend_Loader::loadClass("purchaseOrders");
		Zend_Loader::loadClass("purchaseOrder");
		Zend_Loader::loadClass("purchaseOrderDetail");
		$orders = new purchaseOrders();
		$data = $orders->getOrderExported($userid);
		
		AccountUtility::formatexport($directory,$data) ;
		
		
		$this->assign("host","http://".$localserver);
		$this->setNolayout();
		$this->render();
		
		
	}
	
	public function checkorgAction(){
		
		$userid = $this->getParam("userid");
		$orgid = $this->getParam("orgid");
		$localhost = $this->getParam("localhost");
		
		Zend_Loader::loadClass("User");
		$user = new User();
		
		$user->loadWhere("org_id = ". $orgid . " and id = ". $userid );
		if($user->id){
			$this->assign("continue",1);
		} else {
			$this->assign("continue",0);
		}
		
		//die();
		$this->setNoLayout();
		$this->assign("localhost",$localhost);
		$this->render();
		
	}		

 }

?>	